Skip to content
Draft
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
16 changes: 12 additions & 4 deletions litebox/src/inet_socket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use litebox_broker_protocol::{
error::ErrorCode,
fs::{FileOpenFlags, FileStatusFlags},
socket::{
MAX_TCP_LISTEN_BACKLOG, ShutdownMode, SocketConnectionStatus,
MAX_TCP_LISTEN_BACKLOG, SendFlags as BrokerSendFlags, ShutdownMode, SocketConnectionStatus,
SocketError as BrokerSocketError, SocketOptionName, SocketOptionValue, SocketOutcome,
SocketType,
},
Expand Down Expand Up @@ -360,18 +360,22 @@ impl<Platform: RawSyncPrimitivesProvider + TimeProvider> InetSocket<Platform> {
flags: SendFlags,
destination: Option<SocketAddr>,
) -> Result<usize, SocketWriteError> {
if !flags.is_empty() {
if !flags.difference(SendFlags::REPORT_PENDING_ERROR).is_empty() {
unimplemented!()
}
let mut broker_flags = BrokerSendFlags::NONE;
if flags.contains(SendFlags::REPORT_PENDING_ERROR) {
broker_flags.0 |= BrokerSendFlags::REPORT_PENDING_ERROR.0;
}
if let Some(addr) = destination
&& (addr.port() == 0 || addr.ip().is_unspecified())
{
return Err(SocketWriteError::Unaddressable);
}
if self.is_stream() {
self.write_stream(buf)
self.write_stream(buf, broker_flags)
} else {
self.write_datagram(buf, destination)
self.write_datagram(buf, broker_flags, destination)
}
}

Expand Down Expand Up @@ -485,6 +489,10 @@ bitflags! {
const NOSIGNAL = 0x4000;
/// `MSG_OOB`: sends out-of-band data.
const OOB = 0x1;
/// Report a pending error in place of sending a datagram, as the
/// broker's [`REPORT_PENDING_ERROR`](BrokerSendFlags::REPORT_PENDING_ERROR)
/// defines. A stream send rejects it.
const REPORT_PENDING_ERROR = 1 << 31;
}
}

Expand Down
15 changes: 9 additions & 6 deletions litebox/src/inet_socket/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,16 @@ impl<Platform: RawSyncPrimitivesProvider + TimeProvider> InetSocket<Platform> {
}

/// Writes up to [`MAX_SOCKET_TRANSFER_SIZE`] stream bytes.
pub(super) fn write_stream(&self, buffer: impl WriteBuffer) -> Result<usize, SocketWriteError> {
pub(super) fn write_stream(
&self,
buffer: impl WriteBuffer,
flags: BrokerSendFlags,
) -> Result<usize, SocketWriteError> {
let length = buffer.len().min(MAX_SOCKET_TRANSFER_SIZE as usize);
match self.broker.send_socket(
self.handle,
&buffer.sub_buffer(0, length),
BrokerSendFlags::NONE,
) {
match self
.broker
.send_socket(self.handle, &buffer.sub_buffer(0, length), flags)
{
Ok(SocketOutcome::Completed(sent)) => Ok(sent),
Ok(SocketOutcome::Failed(BrokerSocketError::Shutdown)) => {
Err(SocketWriteError::WriteShutdown)
Expand Down
3 changes: 2 additions & 1 deletion litebox/src/inet_socket/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ impl<Platform: RawSyncPrimitivesProvider + TimeProvider> InetSocket<Platform> {
pub(super) fn write_datagram(
&self,
buffer: impl WriteBuffer,
flags: BrokerSendFlags,
destination: Option<SocketAddr>,
) -> Result<usize, SocketWriteError> {
if buffer.len() > MAX_UDP_DATAGRAM_SIZE as usize {
Expand All @@ -75,7 +76,7 @@ impl<Platform: RawSyncPrimitivesProvider + TimeProvider> InetSocket<Platform> {
};
match self
.broker
.send_to_socket(self.handle, &buffer, BrokerSendFlags::NONE, destination)
.send_to_socket(self.handle, &buffer, flags, destination)
{
Ok(SocketOutcome::Completed(sent)) => Ok(sent),
Ok(SocketOutcome::Failed(BrokerSocketError::Shutdown)) => {
Expand Down
131 changes: 89 additions & 42 deletions litebox_broker_core/src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,12 @@ pub trait PlatformSocket: Send + Sync {
/// socket shut down for writing fails with `Shutdown`. Partial successful
/// sends are invalid. Resource failures are broker errors rather than
/// ordinary socket failures.
///
/// With [`SendFlags::REPORT_PENDING_ERROR`], a pending error the platform
/// holds fails the send in place of sending, and is taken. Without it, the
/// send neither reports nor takes a pending error, which a later status or
/// receive reports: a platform whose host send would take one takes it
/// first and keeps it.
fn send_to(
&self,
data: &dyn WriteBuffer,
Expand Down Expand Up @@ -752,6 +758,9 @@ pub fn create(
/// fails every later attempt the same way. UDP connects complete
/// synchronously, and a failed attempt preserves the previous peer. Policy
/// denial is also a [`SocketOutcome::Failed`] that preserves existing state.
/// A UDP connect to the broadcast address, to which the broker sends no
/// datagrams, is denied so, with `PolicyDenied`, as Linux fails one without
/// `SO_BROADCAST` with `EACCES`.
pub fn connect(
process: &BrokerProcess,
handle: ObjectHandle,
Expand Down Expand Up @@ -822,6 +831,9 @@ fn connect_datagram(
if is_unaddressable(address) {
return Ok(SocketOutcome::Failed(SocketError::ConnectionRefused));
}
if is_broadcast(address) {
return Ok(SocketOutcome::Failed(SocketError::PolicyDenied));
}
Ok(match transport_connect(process, object, address)? {
SocketOutcome::Completed(SocketConnectionStatus::Failed(error)) => {
SocketOutcome::Failed(error)
Expand All @@ -835,6 +847,12 @@ fn is_unaddressable(address: SocketAddrV4) -> bool {
address.port() == 0 || address.ip().is_unspecified()
}

/// Returns whether `address` is the broadcast address, to which the broker
/// sends no datagrams, whatever a socket's `Broadcast` option.
fn is_broadcast(address: SocketAddrV4) -> bool {
*address.ip() == Ipv4Addr::BROADCAST
}

/// Reports the progress of a connection attempt.
///
/// A connected stream is reported connected, so a later [`connect`] fails
Expand Down Expand Up @@ -1309,9 +1327,10 @@ pub fn accept(

/// Sends TCP stream bytes without waiting for readiness.
///
/// A socket shut down for writing fails with `Shutdown` once any connection
/// attempt has finished, and an unconnected socket fails with `NotConnected`.
/// A temporarily full socket, or one whose connection attempt is still being
/// No send flag applies to a stream, so any flag is rejected. A socket shut
/// down for writing fails with `Shutdown` once any connection attempt has
/// finished, and an unconnected socket fails with `NotConnected`. A
/// temporarily full socket, or one whose connection attempt is still being
/// started, fails with [`BrokerError::WouldBlock`], or with
/// [`BrokerError::NonBlockingWouldBlock`] if the socket is non-blocking.
pub fn send(
Expand All @@ -1320,7 +1339,7 @@ pub fn send(
data: &dyn WriteBuffer,
flags: SendFlags,
) -> Result<SocketOutcome<usize>> {
if flags.has_unsupported_bits() || data.len() > MAX_SOCKET_TRANSFER_SIZE as usize {
if flags != SendFlags::NONE || data.len() > MAX_SOCKET_TRANSFER_SIZE as usize {
return Err(BrokerError::UnsupportedOperation);
}
let object = process.authorized_object(handle, ObjectRights::WRITE)?;
Expand Down Expand Up @@ -1403,14 +1422,20 @@ fn transport_send(

/// Sends `data` as one complete datagram without waiting for readiness.
///
/// A pending error fails the send and is consumed, and a socket shut down for
/// writing fails with `Shutdown`. Without `destination`, an unconnected
/// socket fails with `DestinationAddressRequired`. The first valid send with
/// an explicit destination on an unbound datagram socket reserves and binds a
/// guest-visible local endpoint before invoking the platform. A temporarily
/// full socket fails with a pending error if there is one, and otherwise with
/// [`BrokerError::WouldBlock`], or with [`BrokerError::NonBlockingWouldBlock`]
/// if the socket is non-blocking.
/// The destination is checked first: without `destination`, an unconnected
/// socket fails with `DestinationAddressRequired`, and a send to the broadcast
/// address, to which the broker sends no datagrams, fails with `PolicyDenied`.
/// The first valid send with an explicit destination on an unbound datagram
/// socket reserves and binds a guest-visible local endpoint. Then a socket
/// shut down for writing fails with `Shutdown`. A temporarily full socket
/// fails with [`BrokerError::WouldBlock`], or with
/// [`BrokerError::NonBlockingWouldBlock`] if the socket is non-blocking.
///
/// A send leaves pending errors pending unless `flags` has
/// [`SendFlags::REPORT_PENDING_ERROR`]. Then, once the destination is checked,
/// a pending error fails the send and is consumed, before a write shutdown
/// does, and a temporarily full socket fails with a pending error if there is
/// one.
pub fn send_to(
process: &BrokerProcess,
handle: ObjectHandle,
Expand All @@ -1437,33 +1462,36 @@ fn send_datagram(
if !read_socket(object, |socket| is_udp(socket.create_request))? {
return Ok(SocketOutcome::Failed(SocketError::InvalidArgument));
}
if let Some(error) = take_pending_error(object) {
let destination = match route_datagram(process, object, destination)? {
SocketOutcome::Completed(destination) => destination,
SocketOutcome::Failed(error) => return Ok(SocketOutcome::Failed(error)),
};
let report_pending_error = flags.contains(SendFlags::REPORT_PENDING_ERROR);
if report_pending_error && let Some(error) = take_pending_error(object) {
return Ok(SocketOutcome::Failed(error));
}
let (write_shutdown, view) =
read_socket(object, |socket| (socket.write_shutdown, socket.view()))?;
if write_shutdown {
if read_socket(object, |socket| socket.write_shutdown)? {
return Ok(SocketOutcome::Failed(SocketError::Shutdown));
}
if destination.is_none() && view != SocketConnectionStatus::Connected {
return Ok(SocketOutcome::Failed(
SocketError::DestinationAddressRequired,
));
}
finish_datagram_transfer(
object,
transport_send_to(process, object, data, flags, destination),
transport_send_to(object, data, flags, destination),
report_pending_error,
)
}

/// Reports a datagram transfer's pending error in place of a would-block
/// failure, and records any error that follows a failed transfer.
/// Records any error that follows a failed datagram transfer, and, with
/// `report_pending_error`, reports a pending error in place of a would-block
/// failure.
fn finish_datagram_transfer<T>(
object: &RwLock<ObjectEntry>,
result: Result<SocketOutcome<T>>,
report_pending_error: bool,
) -> Result<SocketOutcome<T>> {
match result {
Err(error @ (BrokerError::WouldBlock | BrokerError::NonBlockingWouldBlock)) => {
Err(error @ (BrokerError::WouldBlock | BrokerError::NonBlockingWouldBlock))
if report_pending_error =>
{
match take_pending_error(object) {
Some(error) => Ok(SocketOutcome::Failed(error)),
None => Err(error),
Expand All @@ -1477,25 +1505,32 @@ fn finish_datagram_transfer<T>(
}
}

/// Sends one datagram, first binding an unbound socket.
fn transport_send_to(
/// Checks a datagram's destination, and that the socket has a source for it,
/// first binding an unbound socket, and returns the normalized destination.
fn route_datagram(
process: &BrokerProcess,
object: &RwLock<ObjectEntry>,
data: &dyn WriteBuffer,
flags: SendFlags,
destination: Option<SocketAddrV4>,
) -> Result<SocketOutcome<usize>> {
let length = data.len();
let create_request = read_socket(object, |socket| socket.create_request)?;
) -> Result<SocketOutcome<Option<SocketAddrV4>>> {
let (create_request, view) =
read_socket(object, |socket| (socket.create_request, socket.view()))?;
let destination = match destination {
None if view != SocketConnectionStatus::Connected => {
return Ok(SocketOutcome::Failed(
SocketError::DestinationAddressRequired,
));
}
None => None,
Some(destination) if destination.port() == 0 => {
return Ok(SocketOutcome::Failed(SocketError::InvalidArgument));
}
Some(destination) if is_broadcast(destination) => {
return Ok(SocketOutcome::Failed(SocketError::PolicyDenied));
}
Some(destination) => match normalize_socket_destination(destination) {
Ok(destination) => Some(destination),
Err(error) => return Ok(SocketOutcome::Failed(error)),
},
None => None,
};
if let Some(destination) = destination {
match process.core.policy.authorize_socket_connect(
Expand All @@ -1510,7 +1545,7 @@ fn transport_send_to(
Err(error) => return Err(error),
}
}
let (resource, needs_bind, nonblocking) = {
let (resource, needs_bind) = {
let mut object = object.write();
let ObjectEntry::Socket(socket) = &mut *object else {
return Err(BrokerError::InvalidRights);
Expand All @@ -1531,11 +1566,7 @@ fn transport_send_to(
}
socket.configuration_in_flight = true;
}
(
Arc::clone(&socket.resource),
needs_bind,
socket.status.nonblocking(),
)
(Arc::clone(&socket.resource), needs_bind)
};
if needs_bind {
match reserve_and_bind(process, create_request, &resource, DEFAULT_LOCAL_ADDRESS) {
Expand Down Expand Up @@ -1564,10 +1595,26 @@ fn transport_send_to(
}) {
return Ok(SocketOutcome::Failed(SocketError::InvalidArgument));
}
let outcome = resource
Ok(SocketOutcome::Completed(destination))
}

/// Sends one datagram to a destination [`route_datagram`] returned.
fn transport_send_to(
object: &RwLock<ObjectEntry>,
data: &dyn WriteBuffer,
flags: SendFlags,
destination: Option<SocketAddrV4>,
) -> Result<SocketOutcome<usize>> {
let length = data.len();
let state = socket_state(object)?;
if state.resource_retired {
return Ok(SocketOutcome::Failed(SocketError::NotConnected));
}
let outcome = state
.resource
.platform_socket
.send_to(data, flags, destination)
.map_err(|error| would_block_error(error, nonblocking))?;
.map_err(|error| would_block_error(error, state.nonblocking))?;
if let SocketOutcome::Completed(sent) = outcome
&& sent != length
{
Expand Down Expand Up @@ -1755,7 +1802,7 @@ fn receive_datagram(
{
Ok(SocketOutcome::Failed(SocketError::Shutdown))
}
result => finish_datagram_transfer(object, result),
result => finish_datagram_transfer(object, result, true),
}
}

Expand Down
Loading
Loading