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
use std::net::SocketAddr;
use std::os::fd::RawFd;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use crossbeam_channel::Sender;
/// Configuration for the centralized acceptor thread.
pub struct AcceptorConfig {
/// The listening socket fd.
pub listen_fd: RawFd,
/// Per-worker channels to send accepted (fd, peer_addr) pairs.
pub worker_channels: Vec<Sender<(RawFd, SocketAddr)>>,
/// Per-worker wake handles to wake the event loop after sending a connection.
pub worker_wake_handles: Vec<crate::wakeup::WakeHandle>,
/// Shared flag set by ShutdownHandle to signal the acceptor to stop.
#[allow(dead_code)] // stored for future use; acceptor currently uses channel disconnect
pub shutdown_flag: Arc<AtomicBool>,
/// Whether to set TCP_NODELAY on accepted connections.
pub tcp_nodelay: bool,
/// Whether to set SO_TIMESTAMPING on accepted connections.
#[cfg(feature = "timestamps")]
pub timestamps: bool,
}
/// Run the acceptor loop. Terminates when all channels disconnect.
///
/// Accepts connections via blocking `accept4` and distributes raw fds
/// to workers round-robin, waking each worker via eventfd.
pub fn run_acceptor(config: AcceptorConfig) {
let num_workers = config.worker_channels.len();
if num_workers == 0 {
return;
}
let mut next_worker = 0usize;
let mut addr_storage: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
let mut alive = vec![true; num_workers];
let mut alive_count = num_workers;
loop {
let mut addr_len: libc::socklen_t =
std::mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
let fd = accept_nonblock(config.listen_fd, &mut addr_storage, &mut addr_len);
if fd < 0 {
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::EMFILE) | Some(libc::ENFILE) => {
// Too many open files — back off briefly.
std::thread::sleep(std::time::Duration::from_millis(10));
continue;
}
Some(libc::ECONNABORTED) | Some(libc::ECONNRESET) | Some(libc::EPERM) => {
// Connection reset before accept completed, or blocked by
// firewall — retry immediately.
continue;
}
_ => {
// Fatal accept error or listen fd closed.
return;
}
}
}
// Set TCP_NODELAY if configured (skip for Unix domain sockets).
if config.tcp_nodelay && addr_storage.ss_family != libc::AF_UNIX as libc::sa_family_t {
let optval: libc::c_int = 1;
unsafe {
libc::setsockopt(
fd,
libc::IPPROTO_TCP,
libc::TCP_NODELAY,
&optval as *const _ as *const libc::c_void,
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
);
}
}
// Set SO_TIMESTAMPING for kernel-level RX timestamps.
#[cfg(feature = "timestamps")]
if config.timestamps {
let flags: libc::c_int = (libc::SOF_TIMESTAMPING_SOFTWARE
| libc::SOF_TIMESTAMPING_RX_SOFTWARE)
as libc::c_int;
unsafe {
libc::setsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_TIMESTAMPING,
&flags as *const _ as *const libc::c_void,
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
);
}
}
// Parse peer address from the sockaddr_storage filled by accept4.
let peer_addr = sockaddr_to_socket_addr(&addr_storage)
.unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 0)));
// Round-robin pick a live worker. Try up to num_workers times.
let mut sent = false;
for _ in 0..num_workers {
let worker_idx = next_worker % num_workers;
next_worker = next_worker.wrapping_add(1);
if !alive[worker_idx] {
continue;
}
if config.worker_channels[worker_idx]
.send((fd, peer_addr))
.is_err()
{
// Worker has exited — mark dead.
alive[worker_idx] = false;
alive_count -= 1;
if alive_count == 0 {
unsafe {
libc::close(fd);
}
return;
}
continue;
}
// Wake the worker's event loop.
config.worker_wake_handles[worker_idx].wake();
sent = true;
break;
}
if !sent {
// All workers dead.
unsafe {
libc::close(fd);
}
return;
}
}
}
/// Accept a connection and set it to non-blocking + close-on-exec.
///
/// On Linux, uses `accept4(SOCK_NONBLOCK | SOCK_CLOEXEC)` for a single syscall.
/// On other platforms, falls back to `accept()` + `fcntl()`.
fn accept_nonblock(
listen_fd: libc::c_int,
addr: &mut libc::sockaddr_storage,
addr_len: &mut libc::socklen_t,
) -> libc::c_int {
#[cfg(target_os = "linux")]
{
unsafe {
libc::accept4(
listen_fd,
addr as *mut _ as *mut libc::sockaddr,
addr_len,
libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
)
}
}
#[cfg(not(target_os = "linux"))]
{
let fd =
unsafe { libc::accept(listen_fd, addr as *mut _ as *mut libc::sockaddr, addr_len) };
if fd >= 0 {
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFL);
libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
let fd_flags = libc::fcntl(fd, libc::F_GETFD);
libc::fcntl(fd, libc::F_SETFD, fd_flags | libc::FD_CLOEXEC);
}
}
fd
}
}
/// Convert a `sockaddr_storage` (from accept) to a Rust `SocketAddr`.
fn sockaddr_to_socket_addr(storage: &libc::sockaddr_storage) -> Option<SocketAddr> {
match storage.ss_family as libc::c_int {
libc::AF_INET => {
let sa = unsafe { &*(storage as *const _ as *const libc::sockaddr_in) };
let ip = std::net::Ipv4Addr::from(u32::from_be(sa.sin_addr.s_addr));
let port = u16::from_be(sa.sin_port);
Some(SocketAddr::from((ip, port)))
}
libc::AF_INET6 => {
let sa = unsafe { &*(storage as *const _ as *const libc::sockaddr_in6) };
let ip = std::net::Ipv6Addr::from(sa.sin6_addr.s6_addr);
let port = u16::from_be(sa.sin6_port);
Some(SocketAddr::from((ip, port)))
}
_ => None,
}
}