Skip to content
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

Fix an inconsistency in Linux version of TcpListener::accept #67028

Closed
wants to merge 1 commit 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
27 changes: 27 additions & 0 deletions src/libstd/net/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1818,4 +1818,31 @@ mod tests {
let addr = listener.local_addr().unwrap();
TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();
}

#[test]
fn nonblocking_accept() {
let socket_addr = next_test_ip4();
let listener = t!(TcpListener::bind(&socket_addr));
t!(listener.set_nonblocking(true));

let _t = thread::spawn(move || {
t!(TcpStream::connect(&("localhost", socket_addr.port())));
thread::sleep(Duration::from_millis(1000));
});

loop {
match listener.accept() {
Ok((mut stream, _)) => {
let mut buf = [0; 2];
match stream.read_exact(&mut buf) {
Ok(_) => panic!("expected error"),
Err(ref e) if e.kind() == ErrorKind::WouldBlock => return,
Err(e) => panic!("unexpected error {:?}", e),
}
}
Err(e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => panic!("unexpected error {:?}", e),
}
}
}
}
15 changes: 13 additions & 2 deletions src/libstd/sys/unix/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,14 @@ impl Socket {
flags: c_int
) -> c_int
}
let res = cvt_r(|| unsafe { accept4(self.0.raw(), storage, len, libc::SOCK_CLOEXEC) });
let is_blocking =
unsafe { (cvt(libc::fcntl(self.0.raw(), libc::F_GETFL))? & libc::O_NONBLOCK) != 0 };
let accept_flags = if is_blocking {
libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK
} else {
libc::SOCK_CLOEXEC
};
let res = cvt_r(|| unsafe { accept4(self.0.raw(), storage, len, accept_flags) });
match res {
Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
Expand Down Expand Up @@ -329,7 +336,11 @@ impl Socket {

pub fn take_error(&self) -> io::Result<Option<io::Error>> {
let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
if raw == 0 {
Ok(None)
} else {
Ok(Some(io::Error::from_raw_os_error(raw as i32)))
}
}
}

Expand Down