Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use alloc::boxed::Box;
use alloc::format;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::mem;
use core::net::SocketAddr;
use core::pin::Pin;
use core::task::{Context, Poll};
use futures::{AsyncRead, AsyncWrite, Future, ready};

use crate::linux::io_uring::ffi::{SOCK_CLOEXEC, SOCK_NONBLOCK, SocketDomain, SocketType};
use crate::linux::io_uring::{
    Close, Fd, IoUring, IoVec, MsgHdr, Read, RecvMsg, SendMsg, Write, socket_addr_to_dual_stack,
};
use crate::linux::net::{NetworkError, Result, SocketBufferAllocation, get_buffer_pool};
use crate::linux::sys::{self, Errno};
use crate::{linux, net};

pub struct Listener {
    ring: Arc<IoUring>,
    fd: Fd,
    local_addr: SocketAddr,
}

// Wrapper futures that handle the io_uring async operations
struct SendFuture {
    ring: Arc<IoUring>,
    fd: Fd,
    buf: Vec<u8>,
    state: UnsafeCell<
        Option<Pin<Box<dyn Future<Output = crate::linux::io_uring::Result<usize>> + Send>>>,
    >,
}

struct RecvFuture {
    ring: Arc<IoUring>,
    fd: Fd,
    buf_len: usize,
    state: UnsafeCell<
        Option<(
            Pin<Box<dyn Future<Output = crate::linux::io_uring::Result<usize>> + Send>>,
            Vec<u8>,
        )>,
    >,
}

struct CloseFuture {
    ring: Arc<IoUring>,
    fd: Fd,
    state: UnsafeCell<
        Option<Pin<Box<dyn Future<Output = crate::linux::io_uring::Result<()>> + Send>>>,
    >,
}

pub struct Stream {
    ring: Arc<IoUring>,
    fd: Fd,
    local_addr: SocketAddr,
    peer_addr: SocketAddr,
    buffer_allocation: Option<SocketBufferAllocation>,

    // Current operations - we'll create them on demand
    current_send: UnsafeCell<Option<SendFuture>>,
    current_recv: UnsafeCell<Option<RecvFuture>>,
    current_close: UnsafeCell<Option<CloseFuture>>,
}

// Make Stream Send + Sync
unsafe impl Send for Stream {}
unsafe impl Sync for Stream {}

impl AsyncWrite for Stream {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<futures::io::Result<usize>> {
        unsafe {
            let this = self.get_unchecked_mut();
            let current_send = &mut *this.current_send.get();

            // Create a new send operation for this buffer
            let send_future = SendFuture {
                ring: this.ring.clone(),
                fd: this.fd,
                buf: buf.to_vec(),
                state: UnsafeCell::new(None),
            };

            *current_send = Some(send_future);

            // Now poll it
            if let Some(send_op) = current_send {
                let state = &mut *send_op.state.get();

                // Create the io_uring future if we haven't yet
                if state.is_none() {
                    let buf_ptr = send_op.buf.as_ptr();
                    let buf_len = send_op.buf.len();
                    let ring = send_op.ring.clone();
                    let fd = send_op.fd;
                    let mut iovec = IoVec {
                        base: buf_ptr as *mut u8,
                        len: buf_len,
                    };
                    let mut msghdr = MsgHdr {
                        name: core::ptr::null_mut(),
                        namelen: 0,
                        iov: &mut iovec as *mut IoVec,
                        iovlen: 1,
                        control: core::ptr::null_mut(),
                        controllen: 0,
                        flags: 0,
                    };
                    // Create MsgHdr for sendmsg
                    let fut = Box::pin(async move {
                        // We need to create IoVec and MsgHdr inside the async block
                        // to ensure they live long enough
                        ring.sendmsg(fd, &msghdr, 0).await.await
                    });

                    *state = Some(fut);
                }

                // Poll the future
                match state.as_mut().unwrap().as_mut().poll(cx) {
                    Poll::Ready(Ok(n)) => {
                        *current_send = None; // Clear the operation
                        Poll::Ready(Ok(n))
                    }
                    Poll::Ready(Err(e)) => {
                        *current_send = None; // Clear the operation
                        Poll::Ready(Err(futures::io::Error::new(
                            futures::io::ErrorKind::Other,
                            format!("io_uring sendmsg error: {}", e),
                        )))
                    }
                    Poll::Pending => Poll::Pending,
                }
            } else {
                unreachable!("Just created send operation");
            }
        }
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<futures::io::Result<()>> {
        // TCP doesn't need explicit flushing
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<futures::io::Result<()>> {
        unsafe {
            let this = self.get_unchecked_mut();
            let current_close = &mut *this.current_close.get();

            // If we haven't started closing yet, create the future
            if current_close.is_none() {
                *current_close = Some(CloseFuture {
                    ring: this.ring.clone(),
                    fd: this.fd,
                    state: UnsafeCell::new(None),
                });
            }

            if let Some(close_op) = current_close {
                let state = &mut *close_op.state.get();

                if state.is_none() {
                    let ring = close_op.ring.clone();
                    let fd = close_op.fd;
                    let fut = Box::pin(async move { ring.close(fd).await.await });
                    *state = Some(fut);
                }

                // Poll the close future
                match state.as_mut().unwrap().as_mut().poll(cx) {
                    Poll::Ready(Ok(())) => {
                        *current_close = None;
                        Poll::Ready(Ok(()))
                    }
                    Poll::Ready(Err(e)) => {
                        *current_close = None;
                        Poll::Ready(Err(futures::io::Error::new(
                            futures::io::ErrorKind::Other,
                            format!("io_uring close error: {}", e),
                        )))
                    }
                    Poll::Pending => Poll::Pending,
                }
            } else {
                unreachable!("Just created close operation");
            }
        }
    }
}

impl AsyncRead for Stream {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<futures::io::Result<usize>> {
        unsafe {
            let this = self.get_unchecked_mut();
            let current_recv = &mut *this.current_recv.get();

            // Create a new recv operation for this buffer
            let recv_future = RecvFuture {
                ring: this.ring.clone(),
                fd: this.fd,
                buf_len: buf.len(),
                state: UnsafeCell::new(None),
            };

            *current_recv = Some(recv_future);

            // Now poll it
            if let Some(recv_op) = current_recv {
                let state = &mut *recv_op.state.get();

                // Create the io_uring future if we haven't yet
                if state.is_none() {
                    let buf_len = recv_op.buf_len;
                    let ring = recv_op.ring.clone();
                    let fd = recv_op.fd;

                    // Allocate buffer for receiving
                    let mut recv_buf = vec![0u8; buf_len];
                    let buf_ptr = recv_buf.as_mut_ptr();
                    let mut iovec = IoVec {
                        base: buf_ptr,
                        len: buf_len,
                    };
                    let mut msghdr = MsgHdr {
                        name: core::ptr::null_mut(),
                        namelen: 0,
                        iov: &mut iovec as *mut IoVec,
                        iovlen: 1,
                        control: core::ptr::null_mut(),
                        controllen: 0,
                        flags: 0,
                    };
                    // Create MsgHdr for recvmsg
                    let fut = Box::pin(async move {
                        // We need to create IoVec and MsgHdr inside the async block
                        // to ensure they live long enough

                        ring.recvmsg(fd, &mut msghdr).await.await
                    });

                    *state = Some((fut, recv_buf));
                }

                // Poll the future
                let (fut, recv_buf) = state.as_mut().unwrap();
                match fut.as_mut().poll(cx) {
                    Poll::Ready(Ok(n)) => {
                        // Copy data to output buffer
                        buf[..n].copy_from_slice(&recv_buf[..n]);
                        *current_recv = None; // Clear the operation
                        Poll::Ready(Ok(n))
                    }
                    Poll::Ready(Err(e)) => {
                        *current_recv = None; // Clear the operation
                        Poll::Ready(Err(futures::io::Error::new(
                            futures::io::ErrorKind::Other,
                            format!("io_uring recvmsg error: {}", e),
                        )))
                    }
                    Poll::Pending => Poll::Pending,
                }
            } else {
                unreachable!("Just created recv operation");
            }
        }
    }
}

impl net::tcp::Stream<linux::runtime::Runtime, linux::runtime::Share> for Stream {
    fn connect(addr: core::net::SocketAddr) -> impl Future<Output = net::Result<Self>>
    where
        Self: Sized,
    {
        async move {
            // Get io_uring instance
            let ring = Arc::new(IoUring::with_capacity(256).map_err(|e| {
                NetworkError::Internal(format!("Failed to create io_uring: {}", e))
            })?);

            // Create socket
            let domain = match addr {
                SocketAddr::V4(_) => SocketDomain::Inet as i32,
                SocketAddr::V6(_) => SocketDomain::Inet6 as i32,
            };

            let fd = ring
                .socket(
                    domain,
                    SocketType::Stream as i32 | SOCK_NONBLOCK | SOCK_CLOEXEC,
                    0,
                )
                .await
                .await
                .map_err(|e| NetworkError::Internal(format!("Failed to create socket: {}", e)))?;

            // Convert address
            let (sock_addr, size) = socket_addr_to_dual_stack(addr);

            // Connect
            ring.connect(fd, sock_addr)
                .await
                .await
                .map_err(|e| NetworkError::ConnectionRefused)?;

            // Get local address - for now just use a placeholder
            let local_addr = addr; // TODO: implement getsockname

            Ok(Stream {
                ring,
                fd,
                local_addr,
                peer_addr: addr,
                buffer_allocation: None,
                current_send: UnsafeCell::new(None),
                current_recv: UnsafeCell::new(None),
                current_close: UnsafeCell::new(None),
            })
        }
    }

    fn local_addr(&self) -> net::Result<core::net::SocketAddr> {
        Ok(self.local_addr)
    }

    fn peer_addr(&self) -> net::Result<core::net::SocketAddr> {
        Ok(self.peer_addr)
    }
}

impl net::tcp::Listener<linux::runtime::Runtime, linux::runtime::Share> for Listener {
    fn bind(addr: core::net::SocketAddr) -> impl Future<Output = net::Result<Self>>
    where
        Self: Sized,
    {
        async move {
            // Get io_uring instance
            let ring = Arc::new(IoUring::with_capacity(256).map_err(|e| {
                NetworkError::Internal(format!("Failed to create io_uring: {}", e))
            })?);

            // Create socket
            let domain = match addr {
                SocketAddr::V4(_) => SocketDomain::Inet as i32,
                SocketAddr::V6(_) => SocketDomain::Inet6 as i32,
            };

            let fd = ring
                .socket(
                    domain,
                    SocketType::Stream as i32 | SOCK_NONBLOCK | SOCK_CLOEXEC,
                    0,
                )
                .await
                .await
                .map_err(|e| NetworkError::Internal(format!("Failed to create socket: {}", e)))?;

            // Convert address
            let (sock_addr, addr_len) = socket_addr_to_dual_stack(addr);

            // Bind the socket
            unsafe {
                sys::bind(
                    *fd,
                    &sock_addr as *const _ as *const sys::SockAddr,
                    addr_len as u32,
                )
                .map_err(|e| NetworkError::AddressInUse)?;
            }

            // Listen with a backlog of 128
            unsafe {
                sys::listen(*fd, 128)
                    .map_err(|e| NetworkError::Internal(format!("Listen failed: {}", e)))?;
            }

            Ok(Listener {
                ring,
                fd,
                local_addr: addr,
            })
        }
    }

    fn accept(&self) -> impl Future<Output = net::Result<(Stream, core::net::SocketAddr)>> {
        async move {
            let (client_fd, sock_addr) = self
                .ring
                .accept(self.fd)
                .await
                .await
                .map_err(|e| NetworkError::Internal(format!("Accept failed: {}", e)))?;

            // TODO: Convert sock_addr back to SocketAddr
            let peer_addr = self.local_addr; // Placeholder

            let stream = Stream {
                ring: self.ring.clone(),
                fd: client_fd,
                local_addr: self.local_addr,
                peer_addr,
                buffer_allocation: None,
                current_send: UnsafeCell::new(None),
                current_recv: UnsafeCell::new(None),
                current_close: UnsafeCell::new(None),
            };

            Ok((stream, peer_addr))
        }
    }

    fn local_addr(&self) -> net::Result<core::net::SocketAddr> {
        Ok(self.local_addr)
    }
}