Skip to content

Commit 474c6e0

Browse files
committed
Auto merge of rust-lang#25818 - sfackler:socket-timeouts, r=alexcrichton
Closes rust-lang#25619 r? @alexcrichton
2 parents a0f028d + b5c6c7e commit 474c6e0

File tree

7 files changed

+325
-9
lines changed

7 files changed

+325
-9
lines changed

src/liblibc/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -6043,7 +6043,6 @@ pub mod funcs {
60436043
use types::common::c95::{c_void};
60446044
use types::os::common::bsd44::{socklen_t, sockaddr, SOCKET};
60456045
use types::os::arch::c95::c_int;
6046-
use types::os::arch::posix88::ssize_t;
60476046

60486047
extern "system" {
60496048
pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> SOCKET;
@@ -6068,7 +6067,7 @@ pub mod funcs {
60686067
flags: c_int) -> c_int;
60696068
pub fn recvfrom(socket: SOCKET, buf: *mut c_void, len: c_int,
60706069
flags: c_int, addr: *mut sockaddr,
6071-
addrlen: *mut c_int) -> ssize_t;
6070+
addrlen: *mut c_int) -> c_int;
60726071
pub fn sendto(socket: SOCKET, buf: *const c_void, len: c_int,
60736072
flags: c_int, addr: *const sockaddr,
60746073
addrlen: c_int) -> c_int;

src/libstd/net/tcp.rs

+111
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use io;
1919
use net::{ToSocketAddrs, SocketAddr, Shutdown};
2020
use sys_common::net as net_imp;
2121
use sys_common::{AsInner, FromInner};
22+
use time::Duration;
2223

2324
/// A structure which represents a TCP stream between a local socket and a
2425
/// remote socket.
@@ -139,6 +140,50 @@ impl TcpStream {
139140
pub fn set_keepalive(&self, seconds: Option<u32>) -> io::Result<()> {
140141
self.0.set_keepalive(seconds)
141142
}
143+
144+
/// Sets the read timeout to the timeout specified.
145+
///
146+
/// If the value specified is `None`, then `read` calls will block
147+
/// indefinitely. It is an error to pass the zero `Duration` to this
148+
/// method.
149+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
150+
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
151+
self.0.set_read_timeout(dur)
152+
}
153+
154+
/// Sets the write timeout to the timeout specified.
155+
///
156+
/// If the value specified is `None`, then `write` calls will block
157+
/// indefinitely. It is an error to pass the zero `Duration` to this
158+
/// method.
159+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
160+
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
161+
self.0.set_write_timeout(dur)
162+
}
163+
164+
/// Returns the read timeout of this socket.
165+
///
166+
/// If the timeout is `None`, then `read` calls will block indefinitely.
167+
///
168+
/// # Note
169+
///
170+
/// Some platforms do not provide access to the current timeout.
171+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
172+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
173+
self.0.read_timeout()
174+
}
175+
176+
/// Returns the write timeout of this socket.
177+
///
178+
/// If the timeout is `None`, then `write` calls will block indefinitely.
179+
///
180+
/// # Note
181+
///
182+
/// Some platforms do not provide access to the current timeout.
183+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
184+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
185+
self.0.write_timeout()
186+
}
142187
}
143188

144189
#[stable(feature = "rust1", since = "1.0.0")]
@@ -262,6 +307,7 @@ mod tests {
262307
use net::test::{next_test_ip4, next_test_ip6};
263308
use sync::mpsc::channel;
264309
use sys_common::AsInner;
310+
use time::Duration;
265311
use thread;
266312

267313
fn each_ip(f: &mut FnMut(SocketAddr)) {
@@ -855,4 +901,69 @@ mod tests {
855901
stream_inner);
856902
assert_eq!(format!("{:?}", stream), compare);
857903
}
904+
905+
#[test]
906+
fn timeouts() {
907+
let addr = next_test_ip4();
908+
let listener = t!(TcpListener::bind(&addr));
909+
910+
let stream = t!(TcpStream::connect(&("localhost", addr.port())));
911+
let dur = Duration::new(15410, 0);
912+
913+
assert_eq!(None, t!(stream.read_timeout()));
914+
915+
t!(stream.set_read_timeout(Some(dur)));
916+
assert_eq!(Some(dur), t!(stream.read_timeout()));
917+
918+
assert_eq!(None, t!(stream.write_timeout()));
919+
920+
t!(stream.set_write_timeout(Some(dur)));
921+
assert_eq!(Some(dur), t!(stream.write_timeout()));
922+
923+
t!(stream.set_read_timeout(None));
924+
assert_eq!(None, t!(stream.read_timeout()));
925+
926+
t!(stream.set_write_timeout(None));
927+
assert_eq!(None, t!(stream.write_timeout()));
928+
}
929+
930+
#[test]
931+
fn test_read_timeout() {
932+
let addr = next_test_ip4();
933+
let listener = t!(TcpListener::bind(&addr));
934+
935+
let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
936+
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
937+
938+
let mut buf = [0; 10];
939+
let wait = Duration::span(|| {
940+
let kind = stream.read(&mut buf).err().expect("expected error").kind();
941+
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
942+
});
943+
assert!(wait > Duration::from_millis(400));
944+
assert!(wait < Duration::from_millis(1600));
945+
}
946+
947+
#[test]
948+
fn test_read_with_timeout() {
949+
let addr = next_test_ip4();
950+
let listener = t!(TcpListener::bind(&addr));
951+
952+
let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
953+
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
954+
955+
let mut other_end = t!(listener.accept()).0;
956+
t!(other_end.write_all(b"hello world"));
957+
958+
let mut buf = [0; 11];
959+
t!(stream.read(&mut buf));
960+
assert_eq!(b"hello world", &buf[..]);
961+
962+
let wait = Duration::span(|| {
963+
let kind = stream.read(&mut buf).err().expect("expected error").kind();
964+
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
965+
});
966+
assert!(wait > Duration::from_millis(400));
967+
assert!(wait < Duration::from_millis(1600));
968+
}
858969
}

src/libstd/net/udp.rs

+99
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use io::{self, Error, ErrorKind};
1818
use net::{ToSocketAddrs, SocketAddr, IpAddr};
1919
use sys_common::net as net_imp;
2020
use sys_common::{AsInner, FromInner};
21+
use time::Duration;
2122

2223
/// A User Datagram Protocol socket.
2324
///
@@ -127,6 +128,42 @@ impl UdpSocket {
127128
pub fn set_time_to_live(&self, ttl: i32) -> io::Result<()> {
128129
self.0.time_to_live(ttl)
129130
}
131+
132+
/// Sets the read timeout to the timeout specified.
133+
///
134+
/// If the value specified is `None`, then `read` calls will block
135+
/// indefinitely. It is an error to pass the zero `Duration` to this
136+
/// method.
137+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
138+
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
139+
self.0.set_read_timeout(dur)
140+
}
141+
142+
/// Sets the write timeout to the timeout specified.
143+
///
144+
/// If the value specified is `None`, then `write` calls will block
145+
/// indefinitely. It is an error to pass the zero `Duration` to this
146+
/// method.
147+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
148+
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
149+
self.0.set_write_timeout(dur)
150+
}
151+
152+
/// Returns the read timeout of this socket.
153+
///
154+
/// If the timeout is `None`, then `read` calls will block indefinitely.
155+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
156+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
157+
self.0.read_timeout()
158+
}
159+
160+
/// Returns the write timeout of this socket.
161+
///
162+
/// If the timeout is `None`, then `write` calls will block indefinitely.
163+
#[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
164+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
165+
self.0.write_timeout()
166+
}
130167
}
131168

132169
impl AsInner<net_imp::UdpSocket> for UdpSocket {
@@ -152,6 +189,7 @@ mod tests {
152189
use net::test::{next_test_ip4, next_test_ip6};
153190
use sync::mpsc::channel;
154191
use sys_common::AsInner;
192+
use time::Duration;
155193
use thread;
156194

157195
fn each_ip(f: &mut FnMut(SocketAddr, SocketAddr)) {
@@ -321,4 +359,65 @@ mod tests {
321359
socket_addr, name, udpsock_inner);
322360
assert_eq!(format!("{:?}", udpsock), compare);
323361
}
362+
363+
#[test]
364+
fn timeouts() {
365+
let addr = next_test_ip4();
366+
367+
let stream = t!(UdpSocket::bind(&addr));
368+
let dur = Duration::new(15410, 0);
369+
370+
assert_eq!(None, t!(stream.read_timeout()));
371+
372+
t!(stream.set_read_timeout(Some(dur)));
373+
assert_eq!(Some(dur), t!(stream.read_timeout()));
374+
375+
assert_eq!(None, t!(stream.write_timeout()));
376+
377+
t!(stream.set_write_timeout(Some(dur)));
378+
assert_eq!(Some(dur), t!(stream.write_timeout()));
379+
380+
t!(stream.set_read_timeout(None));
381+
assert_eq!(None, t!(stream.read_timeout()));
382+
383+
t!(stream.set_write_timeout(None));
384+
assert_eq!(None, t!(stream.write_timeout()));
385+
}
386+
387+
#[test]
388+
fn test_read_timeout() {
389+
let addr = next_test_ip4();
390+
391+
let mut stream = t!(UdpSocket::bind(&addr));
392+
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
393+
394+
let mut buf = [0; 10];
395+
let wait = Duration::span(|| {
396+
let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
397+
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
398+
});
399+
assert!(wait > Duration::from_millis(400));
400+
assert!(wait < Duration::from_millis(1600));
401+
}
402+
403+
#[test]
404+
fn test_read_with_timeout() {
405+
let addr = next_test_ip4();
406+
407+
let mut stream = t!(UdpSocket::bind(&addr));
408+
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
409+
410+
t!(stream.send_to(b"hello world", &addr));
411+
412+
let mut buf = [0; 11];
413+
t!(stream.recv_from(&mut buf));
414+
assert_eq!(b"hello world", &buf[..]);
415+
416+
let wait = Duration::span(|| {
417+
let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
418+
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
419+
});
420+
assert!(wait > Duration::from_millis(400));
421+
assert!(wait < Duration::from_millis(1600));
422+
}
324423
}

src/libstd/sys/common/net.rs

+39-7
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@ use str::from_utf8;
2020
use sys::c;
2121
use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
2222
use sys_common::{AsInner, FromInner, IntoInner};
23+
use time::Duration;
2324

2425
////////////////////////////////////////////////////////////////////////////////
2526
// sockaddr and misc bindings
2627
////////////////////////////////////////////////////////////////////////////////
2728

28-
fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
29+
pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
2930
payload: T) -> io::Result<()> {
3031
unsafe {
3132
let payload = &payload as *const T as *const c_void;
@@ -35,16 +36,15 @@ fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
3536
}
3637
}
3738

38-
#[allow(dead_code)]
39-
fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
39+
pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
4040
val: c_int) -> io::Result<T> {
4141
unsafe {
4242
let mut slot: T = mem::zeroed();
4343
let mut len = mem::size_of::<T>() as socklen_t;
44-
let ret = try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
45-
&mut slot as *mut _ as *mut _,
46-
&mut len)));
47-
assert_eq!(ret as usize, mem::size_of::<T>());
44+
try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
45+
&mut slot as *mut _ as *mut _,
46+
&mut len)));
47+
assert_eq!(len as usize, mem::size_of::<T>());
4848
Ok(slot)
4949
}
5050
}
@@ -220,6 +220,22 @@ impl TcpStream {
220220
Ok(())
221221
}
222222

223+
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
224+
self.inner.set_timeout(dur, libc::SO_RCVTIMEO)
225+
}
226+
227+
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
228+
self.inner.set_timeout(dur, libc::SO_SNDTIMEO)
229+
}
230+
231+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
232+
self.inner.timeout(libc::SO_RCVTIMEO)
233+
}
234+
235+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
236+
self.inner.timeout(libc::SO_SNDTIMEO)
237+
}
238+
223239
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
224240
self.inner.read(buf)
225241
}
@@ -471,6 +487,22 @@ impl UdpSocket {
471487
pub fn duplicate(&self) -> io::Result<UdpSocket> {
472488
self.inner.duplicate().map(|s| UdpSocket { inner: s })
473489
}
490+
491+
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
492+
self.inner.set_timeout(dur, libc::SO_RCVTIMEO)
493+
}
494+
495+
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
496+
self.inner.set_timeout(dur, libc::SO_SNDTIMEO)
497+
}
498+
499+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
500+
self.inner.timeout(libc::SO_RCVTIMEO)
501+
}
502+
503+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
504+
self.inner.timeout(libc::SO_SNDTIMEO)
505+
}
474506
}
475507

476508
impl FromInner<Socket> for UdpSocket {

0 commit comments

Comments
 (0)