Skip to content

std: sys: net: uefi: tcp4: Add timeout support #143568

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
41 changes: 29 additions & 12 deletions library/std/src/sys/net/connection/uefi/mod.rs
Original file line number Diff line number Diff line change
@@ -1,45 +1,62 @@
use crate::fmt;
use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
use crate::sync::{Arc, Mutex};
use crate::sys::unsupported;
use crate::time::Duration;

mod tcp;
pub(crate) mod tcp4;

pub struct TcpStream(tcp::Tcp);
pub struct TcpStream {
inner: tcp::Tcp,
read_timeout: Arc<Mutex<Option<Duration>>>,
write_timeout: Arc<Mutex<Option<Duration>>>,
}

impl TcpStream {
pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
tcp::Tcp::connect(addr?).map(Self)
let inner = tcp::Tcp::connect(addr?, None)?;
Ok(Self {
inner,
read_timeout: Arc::new(Mutex::new(None)),
write_timeout: Arc::new(Mutex::new(None)),
})
}

pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result<TcpStream> {
unsupported()
pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
let inner = tcp::Tcp::connect(addr, Some(timeout))?;
Ok(Self {
inner,
read_timeout: Arc::new(Mutex::new(None)),
write_timeout: Arc::new(Mutex::new(None)),
})
}

pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
unsupported()
pub fn set_read_timeout(&self, t: Option<Duration>) -> io::Result<()> {
self.read_timeout.set(t).unwrap();
Ok(())
}

pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
unsupported()
pub fn set_write_timeout(&self, t: Option<Duration>) -> io::Result<()> {
self.write_timeout.set(t).unwrap();
Ok(())
}

pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
unsupported()
Ok(self.read_timeout.get_cloned().unwrap())
}

pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
unsupported()
Ok(self.write_timeout.get_cloned().unwrap())
}

pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
unsupported()
}

pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
self.inner.read(buf, self.read_timeout()?)
}

pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
Expand All @@ -56,7 +73,7 @@ impl TcpStream {
}

pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
self.inner.write(buf, self.write_timeout()?)
}

pub fn write_vectored(&self, buf: &[IoSlice<'_>]) -> io::Result<usize> {
Expand Down
13 changes: 7 additions & 6 deletions library/std/src/sys/net/connection/uefi/tcp.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
use super::tcp4;
use crate::io;
use crate::net::SocketAddr;
use crate::time::Duration;

pub(crate) enum Tcp {
V4(tcp4::Tcp4),
}

impl Tcp {
pub(crate) fn connect(addr: &SocketAddr) -> io::Result<Self> {
pub(crate) fn connect(addr: &SocketAddr, timeout: Option<Duration>) -> io::Result<Self> {
match addr {
SocketAddr::V4(x) => {
let temp = tcp4::Tcp4::new()?;
temp.configure(true, Some(x), None)?;
temp.connect()?;
temp.connect(timeout)?;
Ok(Tcp::V4(temp))
}
SocketAddr::V6(_) => todo!(),
}
}

pub(crate) fn write(&self, buf: &[u8]) -> io::Result<usize> {
pub(crate) fn write(&self, buf: &[u8], timeout: Option<Duration>) -> io::Result<usize> {
match self {
Self::V4(client) => client.write(buf),
Self::V4(client) => client.write(buf, timeout),
}
}

pub(crate) fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
pub(crate) fn read(&self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<usize> {
match self {
Self::V4(client) => client.read(buf),
Self::V4(client) => client.read(buf, timeout),
}
}
}
68 changes: 61 additions & 7 deletions library/std/src/sys/net/connection/uefi/tcp4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::net::SocketAddrV4;
use crate::ptr::NonNull;
use crate::sync::atomic::{AtomicBool, Ordering};
use crate::sys::pal::helpers;
use crate::time::{Duration, Instant};

const TYPE_OF_SERVICE: u8 = 8;
const TIME_TO_LIVE: u8 = 255;
Expand Down Expand Up @@ -66,7 +67,7 @@ impl Tcp4 {
if r.is_error() { Err(crate::io::Error::from_raw_os_error(r.as_usize())) } else { Ok(()) }
}

pub(crate) fn connect(&self) -> io::Result<()> {
pub(crate) fn connect(&self, timeout: Option<Duration>) -> io::Result<()> {
let evt = unsafe { self.create_evt() }?;
let completion_token =
tcp4::CompletionToken { event: evt.as_ptr(), status: Status::SUCCESS };
Expand All @@ -79,7 +80,7 @@ impl Tcp4 {
return Err(io::Error::from_raw_os_error(r.as_usize()));
}

self.wait_for_flag();
unsafe { self.wait_or_cancel(timeout, &mut conn_token.completion_token) }?;

if completion_token.status.is_error() {
Err(io::Error::from_raw_os_error(completion_token.status.as_usize()))
Expand All @@ -88,7 +89,7 @@ impl Tcp4 {
}
}

pub(crate) fn write(&self, buf: &[u8]) -> io::Result<usize> {
pub(crate) fn write(&self, buf: &[u8], timeout: Option<Duration>) -> io::Result<usize> {
let evt = unsafe { self.create_evt() }?;
let completion_token =
tcp4::CompletionToken { event: evt.as_ptr(), status: Status::SUCCESS };
Expand Down Expand Up @@ -119,7 +120,7 @@ impl Tcp4 {
return Err(io::Error::from_raw_os_error(r.as_usize()));
}

self.wait_for_flag();
unsafe { self.wait_or_cancel(timeout, &mut token.completion_token) }?;

if completion_token.status.is_error() {
Err(io::Error::from_raw_os_error(completion_token.status.as_usize()))
Expand All @@ -128,7 +129,7 @@ impl Tcp4 {
}
}

pub(crate) fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
pub(crate) fn read(&self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<usize> {
let evt = unsafe { self.create_evt() }?;
let completion_token =
tcp4::CompletionToken { event: evt.as_ptr(), status: Status::SUCCESS };
Expand Down Expand Up @@ -158,7 +159,7 @@ impl Tcp4 {
return Err(io::Error::from_raw_os_error(r.as_usize()));
}

self.wait_for_flag();
unsafe { self.wait_or_cancel(timeout, &mut token.completion_token) }?;

if completion_token.status.is_error() {
Err(io::Error::from_raw_os_error(completion_token.status.as_usize()))
Expand All @@ -167,6 +168,50 @@ impl Tcp4 {
}
}

/// Wait for an event to finish. This is checked by an atomic boolean that is supposed to be set
/// to true in the event callback.
///
/// Optionally, allow specifying a timeout.
///
/// If a timeout is provided, the operation (specified by its `EFI_TCP4_COMPLETION_TOKEN`) is
/// canceled and Error of kind TimedOut is returned.
///
/// # SAFETY
///
/// Pointer to a valid `EFI_TCP4_COMPLETION_TOKEN`
unsafe fn wait_or_cancel(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and on cancel, a docstring that includes the # Safety requirements would be good to add.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you fill in the rest of the docstring (say what behavior is, not just the safety req).

nit: I don't think it's a safety requirement that the token come from connect/accept/transmit/receive, just a logical requirement. The spec says EFI_NOT_FOUND is returned is the token is unknown, so the safety requirement is probably just that the token pointer is valid.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added

&self,
timeout: Option<Duration>,
token: *mut tcp4::CompletionToken,
) -> io::Result<()> {
if !self.wait_for_flag(timeout) {
let _ = unsafe { self.cancel(token) };
return Err(io::Error::new(io::ErrorKind::TimedOut, "Operation Timed out"));
}

Ok(())
}

/// Abort an asynchronous connection, listen, transmission or receive request.
///
/// If token is NULL, then all pending tokens issued by EFI_TCP4_PROTOCOL.Connect(),
/// EFI_TCP4_PROTOCOL.Accept(), EFI_TCP4_PROTOCOL.Transmit() or EFI_TCP4_PROTOCOL.Receive() are
/// aborted.
///
/// # SAFETY
///
/// Pointer to a valid `EFI_TCP4_COMPLETION_TOKEN` or NULL
unsafe fn cancel(&self, token: *mut tcp4::CompletionToken) -> io::Result<()> {
let protocol = self.protocol.as_ptr();

let r = unsafe { ((*protocol).cancel)(protocol, token) };
if r.is_error() {
return Err(io::Error::from_raw_os_error(r.as_usize()));
} else {
Ok(())
}
}

unsafe fn create_evt(&self) -> io::Result<helpers::OwnedEvent> {
self.flag.store(false, Ordering::Relaxed);
helpers::OwnedEvent::new(
Expand All @@ -177,10 +222,19 @@ impl Tcp4 {
)
}

fn wait_for_flag(&self) {
fn wait_for_flag(&self, timeout: Option<Duration>) -> bool {
let start = Instant::now();

while !self.flag.load(Ordering::Relaxed) {
let _ = self.poll();
if let Some(t) = timeout {
if Instant::now().duration_since(start) >= t {
return false;
}
}
}

true
}

fn poll(&self) -> io::Result<()> {
Expand Down
Loading