Skip to main content

network/socket/
udp.rs

1use core::{
2    future::poll_fn,
3    task::{Context, Poll},
4};
5
6use embassy_futures::block_on;
7use smoltcp::socket::udp;
8
9use crate::{IoErrorKind, IpAddress, Port, Result, SocketContext, UdpMetadata};
10
11pub struct UdpSocket {
12    context: SocketContext,
13}
14
15impl UdpSocket {
16    pub(crate) fn new(context: SocketContext) -> Self {
17        Self { context }
18    }
19
20    pub async fn with<F, R>(&self, f: F) -> R
21    where
22        F: FnOnce(&udp::Socket<'static>) -> R,
23    {
24        self.context.with(f).await
25    }
26
27    pub async fn with_mutable<F, R>(&self, f: F) -> R
28    where
29        F: FnOnce(&mut udp::Socket<'static>) -> R,
30    {
31        self.context.with_mutable(f).await
32    }
33
34    pub fn poll_with<F, R>(&self, context: &mut Context<'_>, f: F) -> Poll<R>
35    where
36        F: FnOnce(&udp::Socket, &mut Context<'_>) -> Poll<R>,
37    {
38        self.context.poll_with(context, f)
39    }
40
41    pub fn poll_with_mutable<F, R>(&self, context: &mut Context<'_>, f: F) -> Poll<R>
42    where
43        F: FnOnce(&mut udp::Socket, &mut Context<'_>) -> Poll<R>,
44    {
45        self.context.poll_with_mutable(context, f)
46    }
47
48    /// Bind to the next ephemeral port the stack allocates, for a client that
49    /// sends first. Returns the bound port.
50    pub async fn bind_ephemeral(&mut self) -> Result<Port> {
51        let port = self
52            .context
53            .stack
54            .with_mutable(|stack| stack.get_next_port())
55            .await;
56        self.bind(port).await?;
57        Ok(port)
58    }
59
60    /// Close the current binding and bind a fresh ephemeral port, dropping
61    /// any queued datagrams: each exchange then sends from a new source port.
62    pub async fn rebind_ephemeral(&mut self) -> Result<Port> {
63        self.with_mutable(|socket| socket.close()).await;
64        self.bind_ephemeral().await
65    }
66
67    pub async fn bind(&mut self, port: Port) -> Result<()> {
68        let port = port.into_inner();
69
70        self.with_mutable(|socket| socket.bind(port))
71            .await
72            .map_err(crate::error::udp_bind_error)?;
73
74        Ok(())
75    }
76
77    pub fn poll_send_to(
78        &mut self,
79        context: &mut Context<'_>,
80        buffer: &[u8],
81        metadata: &UdpMetadata,
82    ) -> Poll<Result<()>> {
83        log::debug!("UDP poll_send_to: sending {} bytes", buffer.len());
84        self.poll_with_mutable(context, |socket, cx| {
85            let capacity = socket.payload_send_capacity();
86            log::debug!("UDP send capacity: {}, needed: {}", capacity, buffer.len());
87
88            if capacity < buffer.len() {
89                log::warning!(
90                    "UDP send buffer too small: capacity={}, needed={}",
91                    capacity,
92                    buffer.len()
93                );
94                return Poll::Ready(Err(IoErrorKind::MessageTooLarge));
95            }
96
97            let metadata = metadata.to_smoltcp();
98
99            match socket.send_slice(buffer, metadata) {
100                Ok(()) => {
101                    log::debug!("UDP send_slice succeeded");
102                    Poll::Ready(Ok(()))
103                }
104                Err(udp::SendError::BufferFull) => {
105                    log::information!("UDP send buffer full, registering waker");
106                    socket.register_send_waker(cx.waker());
107                    Poll::Pending
108                }
109                Err(error @ udp::SendError::Unaddressable) => {
110                    let error = crate::error::udp_send_error(
111                        error,
112                        socket.endpoint().port != 0,
113                        !metadata.endpoint.addr.is_unspecified() && metadata.endpoint.port != 0,
114                    );
115                    log::error!("UDP send failed: {}", error.id());
116                    Poll::Ready(Err(error))
117                }
118            }
119        })
120    }
121
122    pub fn poll_receive_from(
123        &self,
124        context: &mut Context<'_>,
125        buffer: &mut [u8],
126    ) -> Poll<Result<(usize, UdpMetadata)>> {
127        log::debug!("UDP poll_receive_from: buffer size={}", buffer.len());
128        self.poll_with_mutable(context, |socket, cx| {
129            log::debug!(
130                "UDP recv: checking socket for data (can_recv={}, buffered={})",
131                socket.can_recv(),
132                socket.recv_queue()
133            );
134            match socket.recv_slice(buffer) {
135                Ok((n, meta)) => {
136                    log::information!("UDP received {} bytes", n);
137                    Poll::Ready(Ok((n, UdpMetadata::from_smoltcp(&meta))))
138                }
139                Err(udp::RecvError::Truncated) => {
140                    log::warning!("UDP receive truncated");
141                    Poll::Ready(Err(IoErrorKind::DatagramTruncated))
142                }
143                Err(udp::RecvError::Exhausted) => {
144                    log::information!(
145                        "UDP receive buffer exhausted (can_recv={}, buffered={})",
146                        socket.can_recv(),
147                        socket.recv_queue()
148                    );
149                    socket.register_recv_waker(cx.waker());
150                    log::information!("UDP receive waker registered");
151                    Poll::Pending
152                }
153            }
154        })
155    }
156
157    pub async fn write_to(&mut self, buffer: &[u8], metadata: &UdpMetadata) -> Result<()> {
158        log::debug!(
159            "UDP write_to: starting async send of {} bytes",
160            buffer.len()
161        );
162        let result = poll_fn(|cx| self.poll_send_to(cx, buffer, metadata)).await;
163        log::debug!("UDP write_to: completed with result {:?}", result.is_ok());
164        result
165    }
166
167    pub async fn read_from(&self, buffer: &mut [u8]) -> Result<(usize, UdpMetadata)> {
168        poll_fn(|cx| {
169            log::information!("Polling UDP read");
170            let r = self.poll_receive_from(cx, buffer);
171            log::information!("UDP read poll completed");
172            r
173        })
174        .await
175    }
176
177    pub fn flush(&mut self) -> impl Future<Output = ()> + '_ {
178        poll_fn(|cx| {
179            self.poll_with_mutable(cx, |socket, cx| {
180                if socket.can_send() {
181                    Poll::Ready(())
182                } else {
183                    socket.register_send_waker(cx.waker());
184                    Poll::Pending
185                }
186            })
187        })
188    }
189
190    /// Close the socket in place. The owner drops it afterwards, so one that holds it in a
191    /// registry can close it while it is still registered, and close it again if a
192    /// cancellation interrupts this call.
193    pub async fn close(&mut self) {
194        self.context.closed = true;
195        self.with_mutable(|s| {
196            log::information!("Closing UDP socket : {:?}", s.endpoint());
197            udp::Socket::close(s);
198            log::information!("UDP socket closed");
199        })
200        .await;
201    }
202
203    pub async fn get_endpoint(&self) -> Result<(Option<IpAddress>, Port)> {
204        let endpoint = self.with(udp::Socket::endpoint).await;
205
206        let ip_address = endpoint.addr.as_ref().map(IpAddress::from_smoltcp);
207        let port = Port::from_inner(endpoint.port);
208
209        Ok((ip_address, port))
210    }
211
212    pub async fn get_packet_read_capacity(&self) -> usize {
213        self.with(udp::Socket::packet_recv_capacity).await
214    }
215
216    pub async fn get_packet_write_capacity(&self) -> usize {
217        self.with(udp::Socket::packet_send_capacity).await
218    }
219
220    pub async fn get_payload_read_capacity(&self) -> usize {
221        self.with(udp::Socket::payload_recv_capacity).await
222    }
223
224    pub async fn get_payload_write_capacity(&self) -> usize {
225        self.with(udp::Socket::payload_send_capacity).await
226    }
227
228    pub async fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
229        self.with_mutable(|socket| socket.set_hop_limit(hop_limit))
230            .await
231    }
232}
233
234impl Drop for UdpSocket {
235    fn drop(&mut self) {
236        if self.context.closed {
237            return;
238        }
239        log::warning!("UDP socket dropped without being closed. Forcing closure.");
240        block_on(self.with_mutable(udp::Socket::close));
241    }
242}
243
244#[cfg(test)]
245mod tests {
246
247    extern crate std;
248
249    use crate::tests::initialize;
250
251    use super::*;
252    use smoltcp::phy::PacketMeta;
253
254    #[task::test]
255    async fn test_udp_bind() {
256        let network_manager = initialize().await;
257
258        let mut socket = network_manager
259            .new_udp_socket(1024, 1024, 10, 10, None)
260            .await
261            .expect("Failed to create UDP socket");
262
263        let port = Port::from_inner(10001);
264        let result = socket.bind(port).await;
265
266        assert!(result.is_ok(), "Failed to bind UDP socket");
267
268        let (_ip, bound_port) = socket.get_endpoint().await.expect("Failed to get endpoint");
269        assert_eq!(bound_port, port, "Port mismatch");
270
271        socket.close().await;
272    }
273
274    #[task::test]
275    async fn test_udp_send_receive() {
276        let network_manager = initialize().await;
277
278        // Create sender socket
279        let mut sender = network_manager
280            .new_udp_socket(1024, 1024, 10, 10, None)
281            .await
282            .expect("Failed to create sender socket");
283
284        // Create receiver socket
285        let mut receiver = network_manager
286            .new_udp_socket(65535, 65535, 10, 10, None)
287            .await
288            .expect("Failed to create receiver socket");
289
290        // Bind receiver to a specific port
291        let receiver_port = Port::from_inner(10003);
292        receiver
293            .bind(receiver_port)
294            .await
295            .expect("Failed to bind receiver");
296
297        // Prepare test data
298        let test_data = b"Hello, UDP!";
299
300        let remote_ip: IpAddress = [127, 0, 0, 1].into();
301
302        let metadata = UdpMetadata::new(remote_ip, receiver_port, None, PacketMeta::default());
303
304        sender
305            .bind(Port::from_inner(10002))
306            .await
307            .expect("Failed to bind sender");
308
309        log::information!("Sending data");
310
311        // Send data
312        let send_result = sender.write_to(test_data, &metadata).await;
313        assert_eq!(send_result, Ok(()));
314
315        log::information!("Data sent, waiting to receive...");
316
317        // Receive data
318        let mut buffer = [0u8; 1024];
319        let receive_result = receiver.read_from(&mut buffer).await;
320
321        log::information!("Data received");
322
323        if let Ok((size, _recv_metadata)) = receive_result {
324            assert_eq!(size, test_data.len(), "Received data size mismatch");
325            assert_eq!(&buffer[..size], test_data, "Received data mismatch");
326        }
327
328        sender.close().await;
329        receiver.close().await;
330    }
331
332    #[task::test]
333    async fn test_udp_endpoint() {
334        let network_manager = initialize().await;
335
336        let mut socket = network_manager
337            .new_udp_socket(1024, 1024, 10, 10, None)
338            .await
339            .expect("Failed to create UDP socket");
340
341        // Before binding, endpoint should have port 0
342        let (_ip, port) = socket
343            .get_endpoint()
344            .await
345            .expect("Failed to get initial endpoint");
346        assert_eq!(port.into_inner(), 0, "Initial port should be 0");
347
348        // After binding, endpoint should have the bound port
349        let bind_port = Port::from_inner(10004);
350        socket.bind(bind_port).await.expect("Failed to bind");
351
352        let (_, bound_port) = socket
353            .get_endpoint()
354            .await
355            .expect("Failed to get bound endpoint");
356        assert_eq!(bound_port, bind_port, "Bound port mismatch");
357
358        socket.close().await;
359    }
360
361    #[task::test]
362    async fn test_udp_capacities() {
363        let network_manager = initialize().await;
364
365        let tx_buffer = 2048;
366        let rx_buffer = 1024;
367        let rx_meta = 15;
368        let tx_meta = 20;
369
370        let mut socket = network_manager
371            .new_udp_socket(tx_buffer, rx_buffer, rx_meta, tx_meta, None)
372            .await
373            .expect("Failed to create UDP socket");
374
375        let packet_read_cap = socket.get_packet_read_capacity().await;
376        let packet_write_cap = socket.get_packet_write_capacity().await;
377        let payload_read_cap = socket.get_payload_read_capacity().await;
378        let payload_write_cap = socket.get_payload_write_capacity().await;
379
380        assert_eq!(packet_read_cap, rx_meta, "Packet read capacity mismatch");
381        assert_eq!(packet_write_cap, tx_meta, "Packet write capacity mismatch");
382        assert_eq!(
383            payload_read_cap, rx_buffer,
384            "Payload read capacity mismatch"
385        );
386        assert_eq!(
387            payload_write_cap, tx_buffer,
388            "Payload write capacity mismatch"
389        );
390
391        socket.close().await;
392    }
393}