Skip to main content

abi_application/
network.rs

1use crate::{
2    Network, NetworkAddress, Status, Tcp, TcpListener, Udp, XILA_ADDRESS_IPV4, XILA_ADDRESS_IPV6,
3    XILA_NETWORK_CONNECT, XILA_NETWORK_LISTEN, XILA_NETWORK_RESOLVE, XILA_SHUTDOWN_WRITE,
4    path_input,
5    registry::{self, Handle},
6    suspend_on, suspend_on_cancellable,
7};
8use ::network::{IpAddress, IpEndpoint, IpListenEndpoint, Ipv6, Manager, Port, TcpSocket};
9use alloc::boxed::Box;
10use core::{
11    ffi::{c_char, c_void},
12    slice,
13};
14
15impl NetworkAddress {
16    fn endpoint(self) -> Result<IpEndpoint, Status> {
17        if self.scope_id != 0 || self.reserved != 0 {
18            return Err(Status::InvalidArgument);
19        }
20        let ip = match self.family {
21            XILA_ADDRESS_IPV4 if self.bytes[4..] == [0; 12] => {
22                let [a, b, c, d, ..] = self.bytes;
23                IpAddress::new_ipv4([a, b, c, d])
24            }
25            XILA_ADDRESS_IPV6 => IpAddress::IPv6(Ipv6::from_inner(self.bytes)),
26            _ => return Err(Status::InvalidArgument),
27        };
28        Ok(IpEndpoint::new(ip, Port::new(self.port)))
29    }
30    fn new(ip: IpAddress, port: Port) -> Self {
31        let mut bytes = [0; 16];
32        let family = match ip {
33            IpAddress::IPv4(ip) => {
34                bytes[..4].copy_from_slice(&ip.into_inner());
35                XILA_ADDRESS_IPV4
36            }
37            IpAddress::IPv6(ip) => {
38                bytes = ip.into_inner();
39                XILA_ADDRESS_IPV6
40            }
41        };
42        Self {
43            family,
44            bytes,
45            port: port.into_inner(),
46            reserved: 0,
47            scope_id: 0,
48        }
49    }
50}
51
52impl Network {
53    pub fn new(manager: &'static Manager, rights: u32) -> Result<Self, Status> {
54        if rights & !7 != 0 {
55            return Err(Status::InvalidArgument);
56        }
57        Ok(Self {
58            manager,
59            rights: rights as u8,
60        })
61    }
62    fn require(&self, right: u32) -> Result<(), Status> {
63        if u32::from(self.rights) & right == 0 {
64            Err(Status::PermissionDenied)
65        } else {
66            Ok(())
67        }
68    }
69}
70
71/// Box and unbox the objects the ABI hands out. A `registered` object also lists itself in
72/// the registry of the process that opened it, so the host closes it if the process ends
73/// without doing so. A network capability is granted by the host and owns nothing to close.
74macro_rules! ownership {
75    ($name:ty) => {
76        impl $name {
77            pub fn into_raw(self) -> *mut Self {
78                Box::into_raw(Box::new(self))
79            }
80            /// Reclaim an owned object exactly once.
81            /// # Safety
82            /// Pointer must be live and returned by `into_raw`.
83            pub unsafe fn from_raw(raw: *mut Self) -> Box<Self> {
84                unsafe { Box::from_raw(raw) }
85            }
86        }
87    };
88    ($name:ty, registered, $close:ident) => {
89        impl $name {
90            pub fn into_raw(self) -> *mut Self {
91                registry::register(self)
92            }
93            /// Reclaim an owned object exactly once.
94            /// # Safety
95            /// Pointer must be live and returned by `into_raw`.
96            pub unsafe fn from_raw(raw: *mut Self) -> Self {
97                unsafe { registry::reclaim(raw) }
98            }
99        }
100        impl Handle for $name {
101            unsafe fn close(raw: *mut Self) {
102                // SAFETY: the registry holds only live objects that came from `into_raw`.
103                let _ = unsafe { $close(raw) };
104            }
105        }
106    };
107}
108ownership!(Network);
109ownership!(Tcp, registered, xila_tcp_close);
110ownership!(TcpListener, registered, xila_tcp_listener_close);
111ownership!(Udp, registered, xila_udp_close);
112
113fn status(result: Result<(), Status>) -> Status {
114    result.map_or_else(|e| e, |()| Status::Ok)
115}
116unsafe fn input<'a, T>(p: *const T) -> Result<&'a T, Status> {
117    unsafe { p.as_ref() }.ok_or(Status::InvalidArgument)
118}
119unsafe fn object<'a, T>(p: *mut T) -> Result<&'a mut T, Status> {
120    unsafe { p.as_mut() }.ok_or(Status::InvalidArgument)
121}
122unsafe fn read_buffer<'a>(p: *const c_void, size: usize) -> Result<&'a [u8], Status> {
123    if size > isize::MAX as usize || (size != 0 && p.is_null()) {
124        return Err(Status::InvalidArgument);
125    }
126    Ok(if size == 0 {
127        &[]
128    } else {
129        unsafe { slice::from_raw_parts(p.cast(), size) }
130    })
131}
132unsafe fn write_buffer<'a>(p: *mut c_void, size: usize) -> Result<&'a mut [u8], Status> {
133    if size > isize::MAX as usize || (size != 0 && p.is_null()) {
134        return Err(Status::InvalidArgument);
135    }
136    Ok(if size == 0 {
137        &mut []
138    } else {
139        unsafe { slice::from_raw_parts_mut(p.cast(), size) }
140    })
141}
142/// The local endpoint a listener or a UDP socket binds. The unspecified address of
143/// either family is the wildcard, as in POSIX: smoltcp matches only `None` against
144/// every local address, and would never accept on `0.0.0.0` or `::`. `None` matches
145/// both families, so the listener and the UDP calls drop traffic of the other family
146/// themselves (see [`same_family`]): a wildcard bind keeps its family.
147fn listen_endpoint(endpoint: IpEndpoint) -> IpListenEndpoint {
148    let address = (!endpoint.address.into_smoltcp().is_unspecified()).then_some(endpoint.address);
149    IpListenEndpoint::new(address, endpoint.port)
150}
151
152/// Whether smoltcp's address is of the ABI family `family`.
153fn same_family(family: u32, address: &smoltcp::wire::IpAddress) -> bool {
154    let theirs = match address {
155        smoltcp::wire::IpAddress::Ipv4(_) => XILA_ADDRESS_IPV4,
156        smoltcp::wire::IpAddress::Ipv6(_) => XILA_ADDRESS_IPV6,
157    };
158    theirs == family
159}
160
161/// Whether the listener socket holds a connection from the other family than it was
162/// bound with, which a wildcard listener refuses so that it keeps its family.
163fn foreign_connection(socket: &smoltcp::socket::tcp::Socket, address: NetworkAddress) -> bool {
164    use smoltcp::socket::tcp::State;
165    matches!(socket.state(), State::Established | State::CloseWait)
166        && socket
167            .remote_endpoint()
168            .is_some_and(|remote| !same_family(address.family, &remote.addr))
169}
170
171/// Listen on the listener's address again, after a connection was refused.
172fn listen_again(socket: &mut smoltcp::socket::tcp::Socket, address: NetworkAddress) {
173    if let Ok(endpoint) = address.endpoint() {
174        let _ = socket.listen(listen_endpoint(endpoint).into_smoltcp());
175    }
176}
177
178/// Upper bound on waiting for the stack to send the reset that refuses a cross-family
179/// connection. The stack may never send it: on Ethernet or Wi-Fi the peer's link-layer
180/// address can be gone, and smoltcp retries neighbor discovery forever. When the limit
181/// fires, the listener goes back to listening and the peer sees the refusal only at its
182/// next send, as before.
183const RESET_TIMEOUT_MS: u64 = 1000;
184/// The same limit, in Embassy-time ticks, for the deadline a poll stores on a listener.
185const RESET_TIMEOUT_TICKS: u64 = embassy_time::Duration::from_millis(RESET_TIMEOUT_MS).as_ticks();
186
187/// A listener that has a connection from the other family than it was bound with resets
188/// it, so a wildcard listener keeps its family and the peer is refused at once. Also
189/// waits out a reset that a poll left pending on the closed socket, because `accept`
190/// re-listens on a closed socket and would drop it. Returns whether it did.
191///
192/// The stack sends the reset on its next poll, so it is waited for before listening
193/// again: listening before the reset went out would forget the connection it is sent
194/// on, leaving the peer to see the refusal only once it sends data itself. The wait is
195/// bounded by [`RESET_TIMEOUT_MS`], and the listener listens again whatever the wait
196/// ended on.
197async fn refuse_other_family(socket: &mut TcpSocket, address: NetworkAddress) -> bool {
198    // The check and the abort, in one closure.
199    let refuse = socket
200        .with_mutable(|s| {
201            if foreign_connection(s, address) {
202                s.abort();
203                true
204            } else {
205                // A poll may have aborted a connection and left its reset pending.
206                use smoltcp::socket::tcp::State;
207                s.state() == State::Closed && s.remote_endpoint().is_some()
208            }
209        })
210        .await;
211    if !refuse {
212        return false;
213    }
214    // `flush` completes once the pending reset has been sent; race it against the
215    // limit so a reset the stack cannot send does not hang the listener.
216    let _ = embassy_futures::select::select(
217        socket.flush(),
218        embassy_time::Timer::after_millis(RESET_TIMEOUT_MS),
219    )
220    .await;
221    listen_again_socket(socket, address).await;
222    true
223}
224
225/// [`listen_again`] through the socket's stack lock.
226async fn listen_again_socket(socket: &mut TcpSocket, address: NetworkAddress) {
227    socket.with_mutable(|s| listen_again(s, address)).await;
228}
229
230/// The poll form of [`refuse_other_family`]: a poll cannot wait for the reset, so the
231/// socket is aborted, the task is woken once the reset has been sent, and the listener
232/// then listens again. The deadline stored on the listener bounds that wait: a later
233/// poll listens again after it even if the reset is still pending, and the peer then
234/// sees the refusal only at its next send, as before. Returns whether the connection
235/// was foreign.
236fn refuse_other_family_poll(
237    socket: &mut smoltcp::socket::tcp::Socket,
238    listener: &TcpListener,
239    cx: &mut core::task::Context<'_>,
240) -> bool {
241    use smoltcp::socket::tcp::State;
242    if foreign_connection(socket, listener.address) {
243        socket.abort();
244        let deadline = embassy_time::Instant::now().as_ticks() + RESET_TIMEOUT_TICKS;
245        listener.reset_deadline.lock(|cell| cell.set(deadline));
246        socket.register_send_waker(cx.waker());
247        true
248    } else if socket.state() == State::Closed {
249        // The reset went out, or a waiting connection was reset by its peer, or the
250        // reset is still pending: listen again once it went out or its deadline
251        // fired, so the listener keeps its family. Poll reports nothing instead of
252        // XILA_POLL_ERR meanwhile, which is closer to POSIX.
253        if socket.remote_endpoint().is_none() {
254            listen_again(socket, listener.address);
255        } else {
256            // Read the deadline before arming the timer, so `schedule_wake` never runs
257            // inside the critical section.
258            let deadline = listener.reset_deadline.lock(core::cell::Cell::get);
259            if embassy_time::Instant::now().as_ticks() >= deadline {
260                // The stack could not send the reset within the limit; listen again
261                // and let the peer see the refusal at its next send, as before.
262                listen_again(socket, listener.address);
263            } else {
264                // The reset may still go out before the deadline: wake this poll then
265                // too, in case another waker replaced the one registered at abort, so
266                // the listener re-listens as soon as the RST is sent.
267                socket.register_send_waker(cx.waker());
268                // Also wake this poll at the deadline, to listen again even if the
269                // reset is still pending then.
270                let timer = embassy_time::Timer::at(embassy_time::Instant::from_ticks(deadline));
271                let _ = core::pin::pin!(timer).poll(cx);
272            }
273        }
274        false
275    } else {
276        false
277    }
278}
279
280// Small fixed socket buffers; no ABI-side staging buffer on I/O paths.
281const BUFFER_SIZE: usize = 1024;
282
283/// A new socket, which the caller owns as soon as the future completes.
284async fn new_tcp_socket(network: &Network) -> Result<TcpSocket, Status> {
285    network
286        .manager
287        .new_tcp_socket(BUFFER_SIZE, BUFFER_SIZE, None)
288        .await
289        .map_err(Status::from)
290}
291
292/// A new socket, listening on `address`. The socket lives only inside the future until it
293/// completes, so a process cancelled while it waits drops the future and the socket with it.
294async fn listening_socket(network: &Network, address: NetworkAddress) -> Result<TcpSocket, Status> {
295    let endpoint = address.endpoint()?;
296    let mut socket = new_tcp_socket(network).await?;
297    let listening = socket
298        .with_mutable(|s| s.listen(listen_endpoint(endpoint).into_smoltcp()))
299        .await;
300    if listening.is_err() {
301        socket.close_forced().await;
302        return Err(Status::InvalidArgument);
303    }
304    Ok(socket)
305}
306
307/// Release network authority; existing sockets remain valid. Null succeeds.
308/// # Safety
309/// Objects must be live and calls serialized. Inputs must be readable and outputs
310/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
311/// for their lengths. Owned objects must be released exactly once.
312pub unsafe extern "C" fn xila_network_close(network: *mut Network) -> Status {
313    status(unsafe {
314        if !network.is_null() {
315            drop(Network::from_raw(network));
316        }
317        Ok(())
318    })
319}
320
321/// Connect synchronously; timeout zero waits indefinitely, otherwise milliseconds.
322/// # Safety
323/// Objects must be live and calls serialized. Inputs must be readable and outputs
324/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
325/// for their lengths. Owned objects must be released exactly once.
326pub unsafe extern "C" fn xila_tcp_connect(
327    network: *const Network,
328    address: *const NetworkAddress,
329    timeout_ms: u32,
330    connection: *mut *mut Tcp,
331) -> Status {
332    // Checked here, outside the closure, so the null guard is visible to analysis.
333    if connection.is_null() {
334        return Status::InvalidArgument;
335    }
336    let result = (|| unsafe {
337        let network = input(network)?;
338        let endpoint = input(address)?.endpoint()?;
339        network.require(XILA_NETWORK_CONNECT)?;
340        // The socket exists only inside the future until the connection is made, so a
341        // process cancelled while it connects drops the future and the socket with it.
342        let connected = suspend_on_cancellable(async {
343            let mut inner = new_tcp_socket(network).await?;
344            let result = if timeout_ms == 0 {
345                inner.connect(endpoint.address, endpoint.port).await
346            } else {
347                use embassy_futures::select::{Either, select};
348                let start = time::MonotonicClock::now(&time::EmbassyClock);
349                match select(
350                    inner.connect(endpoint.address, endpoint.port),
351                    // A plain deadline check: embassy-time timers need an Embassy executor
352                    // waker, which the non-coroutine `block_on` fallback does not provide.
353                    // Re-waking yields cleanly inside a coroutine and keeps the deadline
354                    // live under executors that sleep until woken.
355                    core::future::poll_fn(|context| {
356                        if time::MonotonicClock::now(&time::EmbassyClock).saturating_sub(start)
357                            >= core::time::Duration::from_millis(u64::from(timeout_ms))
358                        {
359                            core::task::Poll::Ready(())
360                        } else {
361                            context.waker().wake_by_ref();
362                            core::task::Poll::Pending
363                        }
364                    }),
365                )
366                .await
367                {
368                    Either::First(result) => result,
369                    Either::Second(_) => Err(::network::IoErrorKind::TimedOut),
370                }
371            };
372            if let Err(error) = result {
373                inner.close_forced().await;
374                return Err(Status::from(error));
375            }
376            Ok::<_, Status>(inner)
377        });
378        Ok(Tcp { inner: connected? }.into_raw())
379    })();
380    match result {
381        Ok(value) => {
382            // SAFETY: checked non-null at the top of this function.
383            unsafe { connection.write(value) };
384            Status::Ok
385        }
386        Err(error) => error,
387    }
388}
389
390/// Bind and start a single-slot TCP listener. Port zero is rejected by Core.
391/// # Safety
392/// Objects must be live and calls serialized. Inputs must be readable and outputs
393/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
394/// for their lengths. Owned objects must be released exactly once.
395pub unsafe extern "C" fn xila_tcp_listen(
396    network: *const Network,
397    address: *const NetworkAddress,
398    listener: *mut *mut TcpListener,
399) -> Status {
400    // Checked here, outside the closure, so the null guard is visible to analysis.
401    if listener.is_null() {
402        return Status::InvalidArgument;
403    }
404    let result = (|| unsafe {
405        let network = input(network)?;
406        let address = *input(address)?;
407        address.endpoint()?;
408        network.require(XILA_NETWORK_LISTEN)?;
409        let inner = suspend_on_cancellable(listening_socket(network, address))?;
410        Ok(TcpListener {
411            network: Network::new(network.manager, u32::from(network.rights))?,
412            address,
413            inner,
414            reset_deadline: synchronization::blocking_mutex::Mutex::new(core::cell::Cell::new(0)),
415        }
416        .into_raw())
417    })();
418    match result {
419        Ok(value) => {
420            // SAFETY: checked non-null at the top of this function.
421            unsafe { listener.write(value) };
422            Status::Ok
423        }
424        Err(error) => error,
425    }
426}
427
428/// Wait for a connection and replenish the listener. Run the interface runner independently.
429/// # Safety
430/// Objects must be live and calls serialized. Inputs must be readable and outputs
431/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
432/// for their lengths. Owned objects must be released exactly once.
433pub unsafe extern "C" fn xila_tcp_accept(
434    listener: *mut TcpListener,
435    connection: *mut *mut Tcp,
436) -> Status {
437    // Checked here, outside the closure, so the null guard is visible to analysis.
438    if connection.is_null() {
439        return Status::InvalidArgument;
440    }
441    let result = (|| unsafe {
442        let listener = object(listener)?;
443        listener.network.require(XILA_NETWORK_LISTEN)?;
444        let endpoint = listen_endpoint(listener.address.endpoint()?);
445        let address = listener.address;
446        loop {
447            // A poll may have aborted a connection and left its reset pending: wait it
448            // out and listen again before accepting, because `accept` re-listens on a
449            // closed socket and would drop the pending reset.
450            if suspend_on(refuse_other_family(&mut listener.inner, address)) {
451                continue;
452            }
453            suspend_on(
454                listener
455                    .inner
456                    .accept(endpoint.address.clone(), endpoint.port),
457            )
458            .map_err(Status::from)?;
459            // A wildcard listener takes connections of its own family only.
460            if !suspend_on(refuse_other_family(&mut listener.inner, address)) {
461                break;
462            }
463        }
464        if suspend_on(listener.inner.get_remote_endpoint())
465            .map_err(Status::from)?
466            .is_none()
467        {
468            return Err(Status::ConnectionReset);
469        }
470        let replacement =
471            suspend_on_cancellable(listening_socket(&listener.network, listener.address))?;
472        let inner = core::mem::replace(&mut listener.inner, replacement);
473        Ok(Tcp { inner }.into_raw())
474    })();
475    match result {
476        Ok(value) => {
477            // SAFETY: checked non-null at the top of this function.
478            unsafe { connection.write(value) };
479            Status::Ok
480        }
481        Err(error) => error,
482    }
483}
484
485/// Abort and release the socket and its buffers. Null succeeds; queued data may be lost.
486/// # Safety
487/// Objects must be live and calls serialized. Inputs must be readable and outputs
488/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
489/// for their lengths. Owned objects must be released exactly once.
490pub unsafe extern "C" fn xila_tcp_close(socket: *mut Tcp) -> Status {
491    status(unsafe {
492        if !socket.is_null() {
493            // Closed while still registered: a process cancelled in the middle of this
494            // call leaves the socket to the host, which aborts it again.
495            suspend_on((*socket).inner.close_forced());
496            drop(Tcp::from_raw(socket));
497        }
498        Ok(())
499    })
500}
501
502/// Abort and release the socket and its buffers. Null succeeds; queued data may be lost.
503/// # Safety
504/// Objects must be live and calls serialized. Inputs must be readable and outputs
505/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
506/// for their lengths. Owned objects must be released exactly once.
507pub unsafe extern "C" fn xila_tcp_listener_close(socket: *mut TcpListener) -> Status {
508    status(unsafe {
509        if !socket.is_null() {
510            // Closed while still registered, as for a connection.
511            suspend_on((*socket).inner.close_forced());
512            drop(TcpListener::from_raw(socket));
513        }
514        Ok(())
515    })
516}
517
518/// Gracefully shut down writing. Only XILA_SHUTDOWN_WRITE is supported; reads remain valid.
519/// # Safety
520/// Objects must be live and calls serialized. Inputs must be readable and outputs
521/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
522/// for their lengths. Owned objects must be released exactly once.
523pub unsafe extern "C" fn xila_tcp_shutdown(socket: *mut Tcp, direction: u32) -> Status {
524    status((|| unsafe {
525        let socket = object(socket)?;
526        if direction != XILA_SHUTDOWN_WRITE {
527            return Err(Status::InvalidArgument);
528        }
529        suspend_on(socket.inner.close());
530        Ok(())
531    })())
532}
533
534/// Blocking direct-buffer I/O. Zero size permits null; send may be partial; receive zero means EOF.
535/// # Safety
536/// Objects must be live and calls serialized. Inputs must be readable and outputs
537/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
538/// for their lengths. Owned objects must be released exactly once.
539pub unsafe extern "C" fn xila_tcp_send(
540    socket: *mut Tcp,
541    buffer: *const c_void,
542    size: usize,
543    count: *mut usize,
544) -> Status {
545    // Checked here, outside the closure, so the null guard is visible to analysis.
546    if count.is_null() {
547        return Status::InvalidArgument;
548    }
549    let result = (|| unsafe {
550        let socket = object(socket)?;
551        let buffer = read_buffer(buffer, size)?;
552        let n = if size == 0 {
553            0
554        } else {
555            suspend_on(socket.inner.write(buffer)).map_err(Status::from)?
556        };
557        Ok(n)
558    })();
559    match result {
560        Ok(value) => {
561            // SAFETY: checked non-null at the top of this function.
562            unsafe { count.write(value) };
563            Status::Ok
564        }
565        Err(error) => error,
566    }
567}
568
569/// Blocking direct-buffer I/O. Zero size permits null; send may be partial; receive zero means EOF.
570/// # Safety
571/// Objects must be live and calls serialized. Inputs must be readable and outputs
572/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
573/// for their lengths. Owned objects must be released exactly once.
574pub unsafe extern "C" fn xila_tcp_receive(
575    socket: *mut Tcp,
576    buffer: *mut c_void,
577    size: usize,
578    count: *mut usize,
579) -> Status {
580    // Checked here, outside the closure, so the null guard is visible to analysis.
581    if count.is_null() {
582        return Status::InvalidArgument;
583    }
584    let result = (|| unsafe {
585        let socket = object(socket)?;
586        let buffer = write_buffer(buffer, size)?;
587        let n = if size == 0 {
588            0
589        } else {
590            suspend_on(socket.inner.read(buffer)).map_err(Status::from)?
591        };
592        Ok(n)
593    })();
594    match result {
595        Ok(value) => {
596            // SAFETY: checked non-null at the top of this function.
597            unsafe { count.write(value) };
598            Status::Ok
599        }
600        Err(error) => error,
601    }
602}
603
604/// Read the connection endpoint.
605/// # Safety
606/// Objects must be live and calls serialized. Inputs must be readable and outputs
607/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
608/// for their lengths. Owned objects must be released exactly once.
609pub unsafe extern "C" fn xila_tcp_local_address(
610    socket: *const Tcp,
611    address: *mut NetworkAddress,
612) -> Status {
613    // Checked here, outside the closure, so the null guard is visible to analysis.
614    if address.is_null() {
615        return Status::InvalidArgument;
616    }
617    let result = (|| unsafe {
618        let socket = input(socket)?;
619        let (ip, port) = suspend_on(socket.inner.get_local_endpoint())
620            .map_err(Status::from)?
621            .ok_or(Status::NotConnected)?;
622        Ok(NetworkAddress::new(ip, port))
623    })();
624    match result {
625        Ok(value) => {
626            // SAFETY: checked non-null at the top of this function.
627            unsafe { address.write(value) };
628            Status::Ok
629        }
630        Err(error) => error,
631    }
632}
633
634/// Read the connection endpoint.
635/// # Safety
636/// Objects must be live and calls serialized. Inputs must be readable and outputs
637/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
638/// for their lengths. Owned objects must be released exactly once.
639pub unsafe extern "C" fn xila_tcp_peer_address(
640    socket: *const Tcp,
641    address: *mut NetworkAddress,
642) -> Status {
643    // Checked here, outside the closure, so the null guard is visible to analysis.
644    if address.is_null() {
645        return Status::InvalidArgument;
646    }
647    let result = (|| unsafe {
648        let socket = input(socket)?;
649        let (ip, port) = suspend_on(socket.inner.get_remote_endpoint())
650            .map_err(Status::from)?
651            .ok_or(Status::NotConnected)?;
652        Ok(NetworkAddress::new(ip, port))
653    })();
654    match result {
655        Ok(value) => {
656            // SAFETY: checked non-null at the top of this function.
657            unsafe { address.write(value) };
658            Status::Ok
659        }
660        Err(error) => error,
661    }
662}
663
664/// Bind a UDP socket. Port zero is rejected by Core; one datagram per direction is buffered.
665/// # Safety
666/// Objects must be live and calls serialized. Inputs must be readable and outputs
667/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
668/// for their lengths. Owned objects must be released exactly once.
669pub unsafe extern "C" fn xila_udp_bind(
670    network: *const Network,
671    address: *const NetworkAddress,
672    socket: *mut *mut Udp,
673) -> Status {
674    // Checked here, outside the closure, so the null guard is visible to analysis.
675    if socket.is_null() {
676        return Status::InvalidArgument;
677    }
678    let result = (|| unsafe {
679        let network = input(network)?;
680        let address = input(address)?;
681        let address_family = address.family;
682        let endpoint = address.endpoint()?;
683        network.require(XILA_NETWORK_LISTEN)?;
684        // The socket exists only inside the future until it is bound, as for a connection.
685        let bound = suspend_on_cancellable(async {
686            let mut inner = network
687                .manager
688                .new_udp_socket(BUFFER_SIZE, BUFFER_SIZE, 1, 1, None)
689                .await
690                .map_err(Status::from)?;
691            let result = inner
692                .with_mutable(|s| s.bind(listen_endpoint(endpoint).into_smoltcp()))
693                .await;
694            if result.is_err() {
695                inner.close().await;
696                return Err(Status::InvalidArgument);
697            }
698            Ok::<_, Status>(inner)
699        });
700        Ok(Udp {
701            inner: bound?,
702            rights: network.rights,
703            family: address_family,
704        }
705        .into_raw())
706    })();
707    match result {
708        Ok(value) => {
709            // SAFETY: checked non-null at the top of this function.
710            unsafe { socket.write(value) };
711            Status::Ok
712        }
713        Err(error) => error,
714    }
715}
716
717/// Release a UDP socket. Null succeeds.
718/// # Safety
719/// Objects must be live and calls serialized. Inputs must be readable and outputs
720/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
721/// for their lengths. Owned objects must be released exactly once.
722pub unsafe extern "C" fn xila_udp_close(socket: *mut Udp) -> Status {
723    status(unsafe {
724        if !socket.is_null() {
725            // Closed while still registered, as for TCP: a process cancelled in the middle
726            // of this call leaves the socket to the host, which closes it again.
727            suspend_on((*socket).inner.close());
728            drop(Udp::from_raw(socket));
729        }
730        Ok(())
731    })
732}
733
734/// Nonblocking atomic datagram send, without logging or staging allocation.
735/// # Safety
736/// Objects must be live and calls serialized. Inputs must be readable and outputs
737/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
738/// for their lengths. Owned objects must be released exactly once.
739pub unsafe extern "C" fn xila_udp_send_to(
740    socket: *mut Udp,
741    buffer: *const c_void,
742    size: usize,
743    address: *const NetworkAddress,
744    count: *mut usize,
745) -> Status {
746    // Checked here, outside the closure, so the null guard is visible to analysis.
747    if count.is_null() {
748        return Status::InvalidArgument;
749    }
750    let result = (|| unsafe {
751        let socket = object(socket)?;
752        let destination = input(address)?;
753        let endpoint = destination.endpoint()?;
754        let buffer = read_buffer(buffer, size)?;
755        if u32::from(socket.rights) & XILA_NETWORK_CONNECT == 0 {
756            return Err(Status::PermissionDenied);
757        }
758        if destination.family != socket.family {
759            return Err(Status::AddressFamilyUnsupported);
760        }
761        suspend_on(socket.inner.with_mutable(|s| {
762            if size > s.payload_send_capacity() {
763                return Err(Status::Overflow);
764            }
765            s.send_slice(buffer, endpoint.into_smoltcp())
766                .map_err(|e| match e {
767                    smoltcp::socket::udp::SendError::BufferFull => Status::WouldBlock,
768                    smoltcp::socket::udp::SendError::Unaddressable => Status::HostUnreachable,
769                })
770        }))?;
771        Ok(size)
772    })();
773    match result {
774        Ok(value) => {
775            // SAFETY: checked non-null at the top of this function.
776            unsafe { count.write(value) };
777            Status::Ok
778        }
779        Err(error) => error,
780    }
781}
782
783/// Nonblocking datagram receive. Overflow preserves the datagram; outputs change only on success.
784/// # Safety
785/// Objects must be live and calls serialized. Inputs must be readable and outputs
786/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
787/// for their lengths. Owned objects must be released exactly once.
788pub unsafe extern "C" fn xila_udp_receive_from(
789    socket: *mut Udp,
790    buffer: *mut c_void,
791    size: usize,
792    address: *mut NetworkAddress,
793    count: *mut usize,
794) -> Status {
795    // Checked here, outside the closure, so the null guards are visible to analysis.
796    if count.is_null() || address.is_null() {
797        return Status::InvalidArgument;
798    }
799    let result = (|| {
800        unsafe {
801            let socket = object(socket)?;
802            let buffer = write_buffer(buffer, size)?;
803            let family = socket.family;
804            let (n, endpoint) = suspend_on(socket.inner.with_mutable(|s| {
805                drop_other_family(s, family);
806                // Peek first so overflow preserves the datagram and caller buffer.
807                let (data, _) = s.peek().map_err(|_| Status::WouldBlock)?;
808                if data.len() > size {
809                    return Err(Status::Overflow);
810                }
811                s.recv_slice(buffer).map_err(|_| Status::InputOutput)
812            }))?;
813            Ok((
814                n,
815                NetworkAddress::new(
816                    IpAddress::from_smoltcp(&endpoint.endpoint.addr),
817                    Port::new(endpoint.endpoint.port),
818                ),
819            ))
820        }
821    })();
822    match result {
823        Ok((n, endpoint)) => {
824            // SAFETY: both outputs were checked non-null at the top of this function.
825            unsafe {
826                address.write(endpoint);
827                count.write(n);
828            }
829            Status::Ok
830        }
831        Err(error) => error,
832    }
833}
834
835/// Resolve one address family synchronously. Count is capacity in/results out; capacity zero queries size. Overflow leaves outputs unchanged. DNS allocates inside Core.
836/// # Safety
837/// Objects must be live and calls serialized. Inputs must be readable and outputs
838/// aligned, writable and disjoint from inputs and objects. Buffers must be valid
839/// for their lengths. Owned objects must be released exactly once.
840pub unsafe extern "C" fn xila_network_resolve(
841    network: *const Network,
842    host: *const c_char,
843    host_length: usize,
844    family: u32,
845    addresses: *mut NetworkAddress,
846    count: *mut usize,
847) -> Status {
848    // Checked here, outside the closure, so the null guard is visible to analysis.
849    if count.is_null() {
850        return Status::InvalidArgument;
851    }
852    let result = (|| unsafe {
853        let network = input(network)?;
854        let capacity = *count;
855        if capacity > isize::MAX as usize / core::mem::size_of::<NetworkAddress>()
856            || (capacity != 0 && addresses.is_null())
857        {
858            return Err(Status::InvalidArgument);
859        }
860        let host = path_input(host, host_length)?;
861        if host.is_empty() || host.contains('\0') {
862            return Err(Status::InvalidArgument);
863        }
864        let kind = match family {
865            XILA_ADDRESS_IPV4 => ::network::DnsQueryKind::A,
866            XILA_ADDRESS_IPV6 => ::network::DnsQueryKind::Aaaa,
867            _ => return Err(Status::InvalidArgument),
868        };
869        network.require(XILA_NETWORK_RESOLVE)?;
870        let resolved =
871            suspend_on(network.manager.resolve(host, kind, false, None)).map_err(Status::from)?;
872        let matches = |ip: &&IpAddress| {
873            matches!(
874                (family, ip),
875                (XILA_ADDRESS_IPV4, IpAddress::IPv4(_)) | (XILA_ADDRESS_IPV6, IpAddress::IPv6(_))
876            )
877        };
878        let needed = resolved.iter().filter(matches).count();
879        if capacity == 0 {
880            return Ok(needed);
881        }
882        if needed > capacity {
883            return Err(Status::Overflow);
884        }
885        for (index, ip) in resolved.iter().filter(matches).enumerate() {
886            addresses
887                .add(index)
888                .write(NetworkAddress::new(ip.clone(), Port::new(0)));
889        }
890        Ok(needed)
891    })();
892    match result {
893        Ok(value) => {
894            // SAFETY: checked non-null at the top of this function.
895            unsafe { count.write(value) };
896            Status::Ok
897        }
898        Err(error) => error,
899    }
900}
901
902/// Drop the queued datagrams of the other family than the socket was bound with.
903fn drop_other_family(socket: &mut smoltcp::socket::udp::Socket, family: u32) {
904    while let Ok((_, metadata)) = socket.peek() {
905        if same_family(family, &metadata.endpoint.addr) {
906            break;
907        }
908        let _ = socket.recv();
909    }
910}
911
912pub(crate) fn tcp_readiness(
913    connection: &TcpSocket,
914    cx: &mut core::task::Context<'_>,
915    listener: Option<&TcpListener>,
916    events: u16,
917) -> u16 {
918    use crate::{XILA_POLL_ERR, XILA_POLL_HUP, XILA_POLL_IN, XILA_POLL_OUT};
919    use core::task::Poll;
920    use smoltcp::socket::tcp::State;
921
922    // A listener refuses a connection of the other family before it reports one, so
923    // `poll` and a nonblocking accept never see it. The reset is sent by the stack on
924    // its next poll; the task is woken then, and the listener listens again.
925    if let Some(listener) = listener {
926        let _ = connection.poll_with_mutable(cx, |socket, cx| {
927            Poll::Ready(refuse_other_family_poll(socket, listener, cx))
928        });
929    }
930    let listener = listener.is_some();
931
932    let result = connection.poll_with(cx, |socket, _| {
933        let state = socket.state();
934        let mut ready = 0;
935        if listener {
936            if matches!(state, State::Established | State::CloseWait) {
937                ready |= events & XILA_POLL_IN;
938            } else if state == State::Closed && socket.remote_endpoint().is_none() {
939                // The listener is closed without a connection and could not listen
940                // again: report an error.
941                ready |= XILA_POLL_ERR;
942            }
943        } else {
944            if socket.can_recv() {
945                ready |= events & XILA_POLL_IN;
946            }
947            if socket.can_send() {
948                ready |= events & XILA_POLL_OUT;
949            }
950            if matches!(
951                state,
952                State::CloseWait
953                    | State::Closing
954                    | State::LastAck
955                    | State::TimeWait
956                    | State::Closed
957            ) {
958                ready |= XILA_POLL_HUP;
959            }
960        }
961        Poll::Ready((ready, state))
962    });
963    match result {
964        Poll::Ready((ready, State::Closed)) if !listener => {
965            // A fully closed socket can represent either a FIN or a reset.
966            // Peeking zero bytes asks smoltcp which one without consuming data.
967            match connection.poll_with_mutable(cx, |socket, _| {
968                let reset = matches!(
969                    socket.peek(0),
970                    Err(smoltcp::socket::tcp::RecvError::InvalidState)
971                );
972                Poll::Ready(reset)
973            }) {
974                Poll::Ready(true) => ready | XILA_POLL_ERR,
975                Poll::Ready(false) => ready,
976                Poll::Pending => 0,
977            }
978        }
979        Poll::Ready((ready, _)) => ready,
980        Poll::Pending => 0,
981    }
982}
983
984pub(crate) fn udp_readiness(socket: &Udp, cx: &mut core::task::Context<'_>, events: u16) -> u16 {
985    use crate::{XILA_POLL_ERR, XILA_POLL_IN, XILA_POLL_OUT};
986    use core::task::Poll;
987
988    let family = socket.family;
989    let result = socket.inner.poll_with_mutable(cx, |inner, _| {
990        drop_other_family(inner, family);
991        if !inner.is_open() {
992            return Poll::Ready(XILA_POLL_ERR);
993        }
994        let mut ready = 0;
995        if inner.can_recv() {
996            ready |= events & XILA_POLL_IN;
997        }
998        if inner.can_send() && u32::from(socket.rights) & XILA_NETWORK_CONNECT != 0 {
999            ready |= events & XILA_POLL_OUT;
1000        }
1001        Poll::Ready(ready)
1002    });
1003    match result {
1004        Poll::Ready(ready) => ready,
1005        Poll::Pending => 0,
1006    }
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    extern crate std;
1012    use super::*;
1013    #[test]
1014    fn addresses_and_layout() {
1015        for (ip, port) in [
1016            (IpAddress::new_ipv4([192, 0, 2, 1]), Port::new(1234)),
1017            (
1018                IpAddress::new_ipv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 1]),
1019                Port::new(65535),
1020            ),
1021        ] {
1022            let address = NetworkAddress::new(ip.clone(), port);
1023            assert_eq!(address.endpoint(), Ok(IpEndpoint::new(ip, port)));
1024            for invalid in [
1025                NetworkAddress {
1026                    family: 99,
1027                    ..address
1028                },
1029                NetworkAddress {
1030                    reserved: 1,
1031                    ..address
1032                },
1033                NetworkAddress {
1034                    scope_id: 1,
1035                    ..address
1036                },
1037            ] {
1038                assert_eq!(invalid.endpoint(), Err(Status::InvalidArgument));
1039            }
1040        }
1041        let mut invalid = NetworkAddress::new(IpAddress::new_ipv4([127, 0, 0, 1]), Port::new(80));
1042        invalid.bytes[15] = 1;
1043        assert_eq!(invalid.endpoint(), Err(Status::InvalidArgument));
1044        assert_eq!(core::mem::size_of::<NetworkAddress>(), 28);
1045        std::println!(
1046            "Network={} Tcp={} TcpListener={} Udp={} Address={}",
1047            core::mem::size_of::<Network>(),
1048            core::mem::size_of::<Tcp>(),
1049            core::mem::size_of::<TcpListener>(),
1050            core::mem::size_of::<Udp>(),
1051            core::mem::size_of::<NetworkAddress>()
1052        );
1053    }
1054    #[test]
1055    fn unspecified_address_listens_everywhere() {
1056        let port = Port::new(7000);
1057        for unspecified in [
1058            IpAddress::new_ipv4([0, 0, 0, 0]),
1059            IpAddress::new_ipv6([0; 8]),
1060        ] {
1061            let endpoint = listen_endpoint(IpEndpoint::new(unspecified, port));
1062            assert_eq!(endpoint.address, None);
1063            assert_eq!(endpoint.port, port);
1064        }
1065        let loopback = IpAddress::new_ipv4([127, 0, 0, 1]);
1066        assert_eq!(
1067            listen_endpoint(IpEndpoint::new(loopback.clone(), port)).address,
1068            Some(loopback)
1069        );
1070    }
1071    #[test]
1072    fn wildcard_binds_keep_their_family() {
1073        let v4 = IpAddress::new_ipv4([127, 0, 0, 1]).into_smoltcp();
1074        let v6 = IpAddress::new_ipv6([0, 0, 0, 0, 0, 0, 0, 1]).into_smoltcp();
1075        assert!(same_family(XILA_ADDRESS_IPV4, &v4));
1076        assert!(!same_family(XILA_ADDRESS_IPV4, &v6));
1077        assert!(same_family(XILA_ADDRESS_IPV6, &v6));
1078        assert!(!same_family(XILA_ADDRESS_IPV6, &v4));
1079    }
1080    #[test]
1081    fn null_outputs() {
1082        unsafe {
1083            assert_eq!(
1084                xila_tcp_connect(
1085                    core::ptr::null(),
1086                    core::ptr::null(),
1087                    0,
1088                    core::ptr::null_mut()
1089                ),
1090                Status::InvalidArgument
1091            );
1092            assert_eq!(
1093                xila_udp_receive_from(
1094                    core::ptr::null_mut(),
1095                    core::ptr::null_mut(),
1096                    1,
1097                    core::ptr::null_mut(),
1098                    core::ptr::null_mut()
1099                ),
1100                Status::InvalidArgument
1101            );
1102        }
1103        assert_eq!(
1104            Status::from(::network::IoErrorKind::TimedOut),
1105            Status::TimedOut
1106        );
1107        assert_eq!(
1108            Status::from(::network::IoErrorKind::ResourceBusy),
1109            Status::ResourceBusy
1110        );
1111    }
1112}