open-coroutine-core 0.7.0

The open-coroutine is a simple, efficient and generic coroutine library.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use crate::common::constants::SyscallName;
use crate::common::{get_timeout_time, now};
use crate::impl_display_by_debug;
use std::ffi::{c_int, c_longlong, c_uint};
use std::io::{Error, ErrorKind};
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use windows_sys::core::{PCSTR, PSTR};
use windows_sys::Win32::Foundation::{
    ERROR_INVALID_PARAMETER, FALSE, HANDLE, INVALID_HANDLE_VALUE,
};
use windows_sys::Win32::Networking::WinSock::{
    getsockopt, setsockopt, AcceptEx, WSAGetLastError, WSARecv, WSASend, WSASocketW,
    INVALID_SOCKET, LPCONDITIONPROC, LPWSAOVERLAPPED_COMPLETION_ROUTINE, SEND_RECV_FLAGS, SOCKADDR,
    SOCKADDR_IN, SOCKET, SOCKET_ERROR, SOL_SOCKET, SO_PROTOCOL_INFO, SO_UPDATE_ACCEPT_CONTEXT,
    WSABUF, WSAEINPROGRESS, WSAENETDOWN, WSAPROTOCOL_INFOW, WSA_FLAG_OVERLAPPED, WSA_IO_PENDING,
};
use windows_sys::Win32::Storage::FileSystem::SetFileCompletionNotificationModes;
use windows_sys::Win32::System::WindowsProgramming::FILE_SKIP_SET_EVENT_ON_HANDLE;
use windows_sys::Win32::System::IO::{
    CreateIoCompletionPort, GetQueuedCompletionStatusEx, OVERLAPPED, OVERLAPPED_ENTRY,
};

#[cfg(test)]
mod tests;

/// The overlapped struct we actually used for IOCP.
#[repr(C)]
#[derive(educe::Educe)]
#[educe(Debug)]
pub(crate) struct Overlapped {
    /// The base [`OVERLAPPED`].
    #[educe(Debug(ignore))]
    base: OVERLAPPED,
    from_fd: SOCKET,
    pub token: usize,
    syscall_name: SyscallName,
    socket: SOCKET,
    pub result: c_longlong,
}

impl Default for Overlapped {
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

impl_display_by_debug!(Overlapped);

#[repr(C)]
#[derive(Debug)]
pub(crate) struct Operator<'o> {
    cpu: usize,
    iocp: HANDLE,
    entering: AtomicBool,
    phantom_data: PhantomData<&'o Overlapped>,
}

impl<'o> Operator<'o> {
    pub(crate) fn new(cpu: usize) -> std::io::Result<Self> {
        let iocp =
            unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, std::ptr::null_mut(), 0, 0) };
        if iocp.is_null() {
            return Err(Error::last_os_error());
        }
        Ok(Self {
            cpu,
            iocp,
            entering: AtomicBool::new(false),
            phantom_data: PhantomData,
        })
    }

    /// Associates a new `HANDLE` to this I/O completion port.
    ///
    /// This function will associate the given handle to this port with the
    /// given `token` to be returned in status messages whenever it receives a
    /// notification.
    ///
    /// Any object which is convertible to a `HANDLE` via the `AsRawHandle`
    /// trait can be provided to this function, such as `std::fs::File` and
    /// friends.
    fn add_handle(&self, handle: HANDLE) -> std::io::Result<()> {
        unsafe {
            let ret = CreateIoCompletionPort(handle, self.iocp, self.cpu, 0);
            if ret.is_null()
                && ERROR_INVALID_PARAMETER
                    == TryInto::<u32>::try_into(WSAGetLastError()).expect("overflow")
            {
                // duplicate bind
                return Ok(());
            }
            debug_assert_eq!(ret, self.iocp);
            if SetFileCompletionNotificationModes(
                handle,
                u8::try_from(FILE_SKIP_SET_EVENT_ON_HANDLE).expect("overflow"),
            ) == 0
            {
                return Err(Error::last_os_error());
            }
        }
        Ok(())
    }

    pub(crate) fn select(
        &self,
        timeout: Option<Duration>,
        want: usize,
    ) -> std::io::Result<(usize, Vec<Overlapped>, Option<Duration>)> {
        if self
            .entering
            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            return Ok((0, Vec::new(), timeout));
        }
        let result = self.do_select(timeout, want);
        self.entering.store(false, Ordering::Release);
        result
    }

    #[allow(clippy::cast_ptr_alignment)]
    fn do_select(
        &self,
        timeout: Option<Duration>,
        want: usize,
    ) -> std::io::Result<(usize, Vec<Overlapped>, Option<Duration>)> {
        let start_time = Instant::now();
        let timeout_time = timeout.map_or(u64::MAX, get_timeout_time);
        let mut cq = Vec::new();
        loop {
            let left_ns = timeout_time.saturating_sub(now());
            if left_ns == 0 {
                break;
            }
            let mut entries: Vec<OVERLAPPED_ENTRY> = Vec::with_capacity(1024);
            let uninit = entries.spare_capacity_mut();
            let mut recv_count = 0;
            unsafe {
                let ret = GetQueuedCompletionStatusEx(
                    self.iocp,
                    uninit.as_mut_ptr().cast(),
                    uninit.len().try_into().expect("overflow"),
                    &mut recv_count,
                    left_ns
                        .saturating_div(1_000_000)
                        .try_into()
                        .unwrap_or(u32::MAX),
                    0,
                );
                if FALSE == ret {
                    let e = Error::last_os_error();
                    if ErrorKind::TimedOut == e.kind() {
                        continue;
                    }
                    return Err(e);
                }
                entries.set_len(recv_count as _);
                for entry in entries {
                    let mut cqe = Box::from_raw(entry.lpOverlapped.cast::<Overlapped>());
                    // resolve completed read/write tasks
                    cqe.result = match cqe.syscall_name {
                        SyscallName::accept => {
                            if setsockopt(
                                cqe.socket,
                                SOL_SOCKET,
                                SO_UPDATE_ACCEPT_CONTEXT,
                                std::ptr::from_ref(&cqe.from_fd).cast(),
                                c_int::try_from(size_of::<SOCKET>()).expect("overflow"),
                            ) == 0
                            {
                                cqe.socket.try_into().expect("result overflow")
                            } else {
                                -c_longlong::from(WSAENETDOWN)
                            }
                        }
                        SyscallName::recv
                        | SyscallName::WSARecv
                        | SyscallName::send
                        | SyscallName::WSASend => entry.dwNumberOfBytesTransferred.into(),
                        _ => panic!("unsupported"),
                    };
                    eprintln!("IOCP got:{cqe}");
                    cq.push(*cqe);
                }
            }
            if cq.len() >= want {
                break;
            }
        }
        let cost = Instant::now().saturating_duration_since(start_time);
        Ok((cq.len(), cq, timeout.map(|t| t.saturating_sub(cost))))
    }

    #[allow(warnings)]
    pub(crate) fn async_cancel(&self, user_data: usize) -> std::io::Result<()> {
        todo!("CancelIoEx")
    }

    pub(crate) fn accept(
        &self,
        user_data: usize,
        fd: SOCKET,
        _address: *mut SOCKADDR,
        _address_len: *mut c_int,
    ) -> std::io::Result<()> {
        self.acceptex(user_data, fd, SyscallName::accept)
    }

    pub(crate) fn WSAAccept(
        &self,
        user_data: usize,
        fd: SOCKET,
        _address: *mut SOCKADDR,
        _address_len: *mut c_int,
        lpfncondition: LPCONDITIONPROC,
        _dwcallbackdata: usize,
    ) -> std::io::Result<()> {
        if lpfncondition.is_some() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "the WSAAccept in Operator should be called without lpfncondition!",
            ));
        }
        self.acceptex(user_data, fd, SyscallName::WSAAccept)
    }

    fn acceptex(
        &self,
        user_data: usize,
        fd: SOCKET,
        syscall_name: SyscallName,
    ) -> std::io::Result<()> {
        unsafe {
            let mut sock_info: WSAPROTOCOL_INFOW = std::mem::zeroed();
            let mut sock_info_len = size_of::<WSAPROTOCOL_INFOW>()
                .try_into()
                .expect("sock_info_len overflow");
            if getsockopt(
                fd,
                SOL_SOCKET,
                SO_PROTOCOL_INFO,
                std::ptr::from_mut(&mut sock_info).cast(),
                &mut sock_info_len,
            ) != 0
            {
                return Err(Error::other("get socket info failed"));
            }
            self.add_handle(fd as HANDLE)?;
            let socket = WSASocketW(
                sock_info.iAddressFamily,
                sock_info.iSocketType,
                sock_info.iProtocol,
                &sock_info,
                0,
                WSA_FLAG_OVERLAPPED,
            );
            if INVALID_SOCKET == socket {
                return Err(Error::other(format!("add {syscall_name} operation failed")));
            }
            let size = size_of::<SOCKADDR_IN>()
                .saturating_add(16)
                .try_into()
                .expect("size overflow");
            let overlapped: &'o mut Overlapped = Box::leak(Box::default());
            overlapped.from_fd = fd;
            overlapped.token = user_data;
            overlapped.syscall_name = syscall_name;
            overlapped.socket = socket;
            overlapped.result = -c_longlong::from(WSAENETDOWN);
            let mut buf: Vec<u8> = Vec::with_capacity(size as usize * 2);
            while AcceptEx(
                fd,
                socket,
                buf.as_mut_ptr().cast(),
                0,
                size,
                size,
                std::ptr::null_mut(),
                std::ptr::from_mut(overlapped).cast(),
            ) == FALSE
            {
                if WSA_IO_PENDING == WSAGetLastError() {
                    break;
                }
            }
            eprintln!("add {syscall_name} operation:{overlapped}");
        }
        Ok(())
    }

    pub(crate) fn recv(
        &self,
        user_data: usize,
        fd: SOCKET,
        buf: PSTR,
        len: c_int,
        flags: SEND_RECV_FLAGS,
    ) -> std::io::Result<()> {
        let buf = [WSABUF {
            len: len.try_into().expect("len overflow"),
            buf: buf.cast(),
        }];
        self.wsarecv(
            user_data,
            fd,
            buf.as_ptr(),
            buf.len().try_into().expect("len overflow"),
            std::ptr::null_mut(),
            &mut c_uint::try_from(flags).expect("overflow"),
            None,
            SyscallName::recv,
        )
    }

    pub(crate) fn WSARecv(
        &self,
        user_data: usize,
        fd: SOCKET,
        buf: *const WSABUF,
        dwbuffercount: c_uint,
        lpnumberofbytesrecvd: *mut c_uint,
        lpflags: *mut c_uint,
        lpoverlapped: *mut OVERLAPPED,
        lpcompletionroutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE,
    ) -> std::io::Result<()> {
        if !lpoverlapped.is_null() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "the WSARecv in Operator should be called without lpoverlapped!",
            ));
        }
        self.wsarecv(
            user_data,
            fd,
            buf,
            dwbuffercount,
            lpnumberofbytesrecvd,
            lpflags,
            lpcompletionroutine,
            SyscallName::WSARecv,
        )
    }

    fn wsarecv(
        &self,
        user_data: usize,
        fd: SOCKET,
        buf: *const WSABUF,
        dwbuffercount: c_uint,
        lpnumberofbytesrecvd: *mut c_uint,
        lpflags: *mut c_uint,
        lpcompletionroutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE,
        syscall_name: SyscallName,
    ) -> std::io::Result<()> {
        self.add_handle(fd as HANDLE)?;
        unsafe {
            let overlapped: &'o mut Overlapped = Box::leak(Box::default());
            overlapped.from_fd = fd;
            overlapped.token = user_data;
            overlapped.syscall_name = syscall_name;
            overlapped.result = -c_longlong::from(WSAEINPROGRESS);
            if WSARecv(
                fd,
                buf,
                dwbuffercount,
                lpnumberofbytesrecvd,
                lpflags,
                std::ptr::from_mut(overlapped).cast(),
                lpcompletionroutine,
            ) == SOCKET_ERROR
            {
                let errno = WSAGetLastError();
                if WSA_IO_PENDING != errno {
                    return Err(Error::other(format!(
                        "add {syscall_name} operation failed with {errno}"
                    )));
                }
            }
            eprintln!("add {syscall_name} operation:{overlapped}");
        }
        Ok(())
    }

    pub(crate) fn send(
        &self,
        user_data: usize,
        fd: SOCKET,
        buf: PCSTR,
        len: c_int,
        flags: SEND_RECV_FLAGS,
    ) -> std::io::Result<()> {
        let buf = [WSABUF {
            len: len.try_into().expect("len overflow"),
            buf: buf.cast_mut(),
        }];
        self.wsasend(
            user_data,
            fd,
            buf.as_ptr(),
            buf.len().try_into().expect("len overflow"),
            std::ptr::null_mut(),
            c_uint::try_from(flags).expect("overflow"),
            None,
            SyscallName::send,
        )
    }

    pub(crate) fn WSASend(
        &self,
        user_data: usize,
        fd: SOCKET,
        buf: *const WSABUF,
        dwbuffercount: c_uint,
        lpnumberofbytesrecvd: *mut c_uint,
        dwflags: c_uint,
        lpoverlapped: *mut OVERLAPPED,
        lpcompletionroutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE,
    ) -> std::io::Result<()> {
        if !lpoverlapped.is_null() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "the WSASend in Operator should be called without lpoverlapped!",
            ));
        }
        self.wsasend(
            user_data,
            fd,
            buf,
            dwbuffercount,
            lpnumberofbytesrecvd,
            dwflags,
            lpcompletionroutine,
            SyscallName::WSASend,
        )
    }

    fn wsasend(
        &self,
        user_data: usize,
        fd: SOCKET,
        buf: *const WSABUF,
        dwbuffercount: c_uint,
        lpnumberofbytesrecvd: *mut c_uint,
        dwflags: c_uint,
        lpcompletionroutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE,
        syscall_name: SyscallName,
    ) -> std::io::Result<()> {
        self.add_handle(fd as HANDLE)?;
        unsafe {
            let overlapped: &'o mut Overlapped = Box::leak(Box::default());
            overlapped.from_fd = fd;
            overlapped.token = user_data;
            overlapped.syscall_name = syscall_name;
            overlapped.result = -c_longlong::from(WSAEINPROGRESS);
            if WSASend(
                fd,
                buf,
                dwbuffercount,
                lpnumberofbytesrecvd,
                dwflags,
                std::ptr::from_mut(overlapped).cast(),
                lpcompletionroutine,
            ) == SOCKET_ERROR
            {
                let errno = WSAGetLastError();
                if WSA_IO_PENDING != errno {
                    return Err(Error::other(format!(
                        "add {syscall_name} operation failed with {errno}"
                    )));
                }
            }
            eprintln!("add {syscall_name} operation:{overlapped}");
        }
        Ok(())
    }
}