net_io/gate.rs
1//! The gate seam: admission before any byte is read, a check before every write.
2
3use std::fmt;
4use std::sync::Arc;
5
6use crate::error::{CloseReason, KillReason};
7use crate::id::ConnectionId;
8use crate::info::{ConnectionInfo, GateTag, Lane};
9use crate::sys::KillSlot;
10
11/// Decides who may connect and whether bytes may still leave.
12///
13/// net-io calls `admit` after accept and before any read, `readmit` after a
14/// trusted PROXY header, `check` before every write system call, and `closed`
15/// exactly once when an admitted connection closes. A method that panics counts
16/// as a refusal or a denial (fail closed).
17///
18/// # Examples
19///
20/// ```
21/// use net_io::{Admitted, AdmitStage, CloseReason, ConnectionInfo, Denial, Gate, GateTag, Lane, Refusal, WriteCheck};
22/// use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
23///
24/// /// One global kill switch and a count of open connections.
25/// struct Switch { revoked: AtomicBool, open: AtomicU64 }
26///
27/// impl Gate for Switch {
28/// type Ticket = ();
29/// fn admit(&self, info: &ConnectionInfo, _stage: AdmitStage) -> Result<Admitted<()>, Refusal> {
30/// if self.revoked.load(Ordering::Acquire) {
31/// return Err(Refusal::Reset { code: 1 });
32/// }
33/// let lane = if info.client_addr().is_some_and(|a| a.ip().is_loopback()) { Lane(0) } else { Lane(3) };
34/// self.open.fetch_add(1, Ordering::Relaxed);
35/// Ok(Admitted { lane, ticket: (), tag: GateTag(0) })
36/// }
37/// fn readmit(&self, _ticket: &mut (), _info: &ConnectionInfo) -> Result<(), Refusal> {
38/// Ok(())
39/// }
40/// fn check(&self, _ticket: &mut (), _write: &WriteCheck) -> Result<(), Denial> {
41/// if self.revoked.load(Ordering::Acquire) { Err(Denial { code: 503 }) } else { Ok(()) }
42/// }
43/// fn closed(&self, _ticket: (), _info: &ConnectionInfo, _reason: CloseReason) {
44/// self.open.fetch_sub(1, Ordering::Relaxed);
45/// }
46/// }
47///
48/// let gate = Switch { revoked: AtomicBool::new(false), open: AtomicU64::new(0) };
49/// let info = ConnectionInfo::for_testing("127.0.0.1:9".parse().unwrap());
50/// let admitted = gate.admit(&info, AdmitStage::Accept).unwrap();
51/// assert_eq!(admitted.lane, Lane(0));
52/// ```
53pub trait Gate: Send + Sync + 'static {
54 /// Per-connection state the gate keeps; net-io stores it beside the connection.
55 type Ticket: Send + 'static;
56
57 /// After accept and before any read (`Accept`), on `Server::adopt` (`Adopt`),
58 /// or when a client connection gets a gate (`Dialed`).
59 ///
60 /// It runs on an accept thread (or, for a per-worker listener, the worker), so
61 /// it must return promptly: a stop joins accept threads, and one that never
62 /// returns from `admit` holds `drain`, `shutdown`, and the server's drop.
63 ///
64 /// # Errors
65 ///
66 /// A [`Refusal`] closes the connection without reading: abortively, or after
67 /// its bytes with FIN ([`Refusal::WithBytes`]).
68 fn admit(
69 &self,
70 info: &ConnectionInfo,
71 stage: AdmitStage,
72 ) -> Result<Admitted<Self::Ticket>, Refusal>;
73
74 /// After a trusted PROXY header revealed the real client (`info.real_peer` is set).
75 ///
76 /// There is no default: a gate that does not care about proxies writes `Ok(())`
77 /// on purpose (decision D-060).
78 ///
79 /// # Errors
80 ///
81 /// A [`Refusal`] closes the connection: abortively, or after its bytes with FIN
82 /// and the denial linger ([`Refusal::WithBytes`]).
83 fn readmit(&self, ticket: &mut Self::Ticket, info: &ConnectionInfo) -> Result<(), Refusal>;
84
85 /// Before every write system call. The path where nothing is revoked should be one atomic load.
86 ///
87 /// # Errors
88 ///
89 /// A [`Denial`] wipes pending output, writes the session's denial if no byte of
90 /// the current response has left, and closes the connection: FIN after the
91 /// denial and a linger of at most `Limits::denial_linger` (100 ms by default)
92 /// that reads and discards, so the peer reads the denial instead of a reset; a
93 /// reset at once when no denial went out or the linger is zero.
94 fn check(&self, ticket: &mut Self::Ticket, write: &WriteCheck) -> Result<(), Denial>;
95
96 /// Exactly once per admitted connection, after it closed, with its one close reason.
97 fn closed(&self, ticket: Self::Ticket, info: &ConnectionInfo, reason: CloseReason) {
98 let _ = (ticket, info, reason);
99 }
100}
101
102/// When `Gate::admit` runs.
103///
104/// ```
105/// assert_ne!(net_io::AdmitStage::Accept, net_io::AdmitStage::Dialed);
106/// ```
107#[non_exhaustive]
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
109pub enum AdmitStage {
110 /// After accept, before any read.
111 Accept,
112 /// A dialed connection adopted into a server.
113 Adopt,
114 /// A client connection that got a gate.
115 Dialed,
116}
117
118/// What admission grants.
119///
120/// ```
121/// let a = net_io::Admitted { lane: net_io::Lane(1), ticket: (), tag: net_io::GateTag(5) };
122/// assert_eq!(a.tag.0, 5);
123/// ```
124#[derive(Debug)]
125pub struct Admitted<T> {
126 /// The connection's lane.
127 pub lane: Lane,
128 /// The gate's per-connection state.
129 pub ticket: T,
130 /// The gate's opaque name for the connection, stored in `ConnectionInfo::gate`.
131 pub tag: GateTag,
132}
133
134/// How a connection is refused.
135///
136/// ```
137/// let r = net_io::Refusal::WithBytes { code: 3, bytes: b"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 5\r\n\r\n" };
138/// assert_eq!(r.code(), 3);
139/// ```
140#[non_exhaustive]
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub enum Refusal {
143 /// Close with RST.
144 Reset {
145 /// The gate's code.
146 code: u16,
147 },
148 /// Write these bytes once (non-blocking, at most `Limits::refusal_bytes_max`),
149 /// then FIN: at admission the close follows at once (the accept thread does not
150 /// wait, and input the peer already sent turns it into a reset); after a PROXY
151 /// header (`readmit`) a linger of at most `Limits::denial_linger` reads and
152 /// discards first. RST when nothing was sent or that linger is zero.
153 WithBytes {
154 /// The gate's code.
155 code: u16,
156 /// The reply.
157 bytes: &'static [u8],
158 },
159}
160
161impl Refusal {
162 /// The gate's code.
163 #[must_use]
164 pub fn code(&self) -> u16 {
165 match self {
166 Refusal::Reset { code } | Refusal::WithBytes { code, .. } => *code,
167 }
168 }
169}
170
171/// The write the gate is asked about.
172///
173/// ```
174/// use net_io::{ConnectionId, Lane, WriteCheck};
175/// let w = WriteCheck::new(ConnectionId::new(1).unwrap(), Lane(0), 512, false, None);
176/// assert_eq!(w.bytes, 512);
177/// ```
178#[non_exhaustive]
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub struct WriteCheck {
181 /// The connection.
182 pub id: ConnectionId,
183 /// Its lane.
184 pub lane: Lane,
185 /// The size of the chunk about to be written.
186 pub bytes: u32,
187 /// Whether a byte of the current response already left.
188 pub response_started: bool,
189 /// The tag the session gave `Output::begin_tagged_response`.
190 pub response: Option<GateTag>,
191}
192
193impl WriteCheck {
194 /// Builds a check (for tests of gates).
195 #[must_use]
196 pub fn new(
197 id: ConnectionId,
198 lane: Lane,
199 bytes: u32,
200 response_started: bool,
201 response: Option<GateTag>,
202 ) -> WriteCheck {
203 WriteCheck {
204 id,
205 lane,
206 bytes,
207 response_started,
208 response,
209 }
210 }
211}
212
213/// A gate's refusal of a write.
214///
215/// ```
216/// let d = net_io::Denial { code: 403 };
217/// assert_eq!(d.code, 403);
218/// ```
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub struct Denial {
221 /// The gate's code, given to `Session::on_denied`.
222 pub code: u16,
223}
224
225/// The explicit "no gate": admits every connection in `Lane(0)` with `GateTag(0)` and never denies.
226///
227/// ```
228/// use net_io::{AdmitStage, AllowAll, ConnectionInfo, Gate};
229/// let info = ConnectionInfo::for_testing("127.0.0.1:1".parse().unwrap());
230/// assert!(AllowAll.admit(&info, AdmitStage::Accept).is_ok());
231/// ```
232#[derive(Clone, Copy, Debug, Default)]
233pub struct AllowAll;
234
235impl Gate for AllowAll {
236 type Ticket = ();
237 #[inline(always)]
238 fn admit(&self, _info: &ConnectionInfo, _stage: AdmitStage) -> Result<Admitted<()>, Refusal> {
239 Ok(Admitted {
240 lane: Lane::MOST_IMPORTANT,
241 ticket: (),
242 tag: GateTag(0),
243 })
244 }
245 #[inline(always)]
246 fn readmit(&self, _ticket: &mut (), _info: &ConnectionInfo) -> Result<(), Refusal> {
247 Ok(())
248 }
249 #[inline(always)]
250 fn check(&self, _ticket: &mut (), _write: &WriteCheck) -> Result<(), Denial> {
251 Ok(())
252 }
253}
254
255/// Calls `f`, turning a panic into `None` (fail closed for gate and session hooks).
256pub(crate) fn guarded<R>(f: impl FnOnce() -> R) -> Option<R> {
257 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok()
258}
259
260/// A gate and one connection's ticket, type-erased for `TcpConnection`.
261pub(crate) trait ErasedGate: Send {
262 fn check(&mut self, write: &WriteCheck) -> Result<(), Denial>;
263 /// `Gate::readmit` with the current ticket (a panic refuses).
264 #[cfg_attr(not(feature = "proxy"), allow(dead_code))]
265 fn readmit(&mut self, info: &ConnectionInfo) -> Result<(), Refusal>;
266 fn close(&mut self, info: &ConnectionInfo, reason: CloseReason);
267 fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send>;
268}
269
270/// The erased form of a gate plus its current ticket.
271pub(crate) struct GateCell<G: Gate> {
272 pub(crate) gate: Arc<G>,
273 pub(crate) ticket: Option<G::Ticket>,
274}
275
276impl<G: Gate> ErasedGate for GateCell<G> {
277 fn check(&mut self, write: &WriteCheck) -> Result<(), Denial> {
278 let gate = &self.gate;
279 match self.ticket.as_mut() {
280 Some(ticket) => {
281 guarded(|| gate.check(ticket, write)).unwrap_or(Err(Denial { code: 0 }))
282 }
283 None => Err(Denial { code: 0 }),
284 }
285 }
286
287 fn readmit(&mut self, info: &ConnectionInfo) -> Result<(), Refusal> {
288 let gate = &self.gate;
289 match self.ticket.as_mut() {
290 Some(ticket) => {
291 guarded(|| gate.readmit(ticket, info)).unwrap_or(Err(Refusal::Reset { code: 0 }))
292 }
293 None => Err(Refusal::Reset { code: 0 }),
294 }
295 }
296
297 fn close(&mut self, info: &ConnectionInfo, reason: CloseReason) {
298 if let Some(ticket) = self.ticket.take() {
299 let gate = &self.gate;
300 let _ = guarded(|| gate.closed(ticket, info, reason));
301 }
302 }
303
304 fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
305 self
306 }
307}
308
309/// Closes one connection abortively from any thread.
310///
311/// The owning thread does the close; the killer only sets a flag and wakes it,
312/// so it can never close a reused descriptor number.
313///
314/// # Examples
315///
316/// ```no_run
317/// use net_io::KillReason;
318/// let mut conn = net_io::connect("127.0.0.1:7000")?;
319/// let kill = conn.kill_handle();
320/// std::thread::spawn(move || {
321/// std::thread::sleep(std::time::Duration::from_secs(1));
322/// kill.kill(KillReason(1));
323/// });
324/// let mut buf = [0u8; 16];
325/// assert!(matches!(conn.recv(&mut buf), Err(net_io::NetError::Killed { .. })));
326/// # Ok::<(), net_io::NetError>(())
327/// ```
328#[derive(Clone)]
329pub struct KillHandle {
330 pub(crate) slot: Arc<KillSlot>,
331 pub(crate) generation: u32,
332 pub(crate) id: ConnectionId,
333}
334
335impl KillHandle {
336 /// Kills the connection; `false` if it already closed (or was already killed).
337 pub fn kill(&self, reason: KillReason) -> bool {
338 self.slot.kill(self.generation, reason)
339 }
340
341 /// The connection's id.
342 #[must_use]
343 pub fn id(&self) -> ConnectionId {
344 self.id
345 }
346
347 /// Whether the connection is still open: a snapshot, for diagnostics only.
348 #[must_use]
349 pub fn is_open(&self) -> bool {
350 self.slot.is_open(self.generation)
351 }
352}
353
354impl fmt::Debug for KillHandle {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("KillHandle")
357 .field("id", &self.id)
358 .field("open", &self.is_open())
359 .finish()
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 struct Panics;
368 impl Gate for Panics {
369 type Ticket = ();
370 fn admit(&self, _: &ConnectionInfo, _: AdmitStage) -> Result<Admitted<()>, Refusal> {
371 Err(Refusal::Reset { code: 1 })
372 }
373 fn readmit(&self, _: &mut (), _: &ConnectionInfo) -> Result<(), Refusal> {
374 Ok(())
375 }
376 #[allow(clippy::panic)]
377 fn check(&self, _: &mut (), _: &WriteCheck) -> Result<(), Denial> {
378 panic!("gate bug")
379 }
380 }
381
382 #[test]
383 fn test_gate_panic_in_check_denies() {
384 let mut cell = GateCell {
385 gate: Arc::new(Panics),
386 ticket: Some(()),
387 };
388 let w = WriteCheck::new(ConnectionId::new(1).unwrap(), Lane(0), 1, false, None);
389 let prev = std::panic::take_hook();
390 std::panic::set_hook(Box::new(|_| {}));
391 let r = cell.check(&w);
392 std::panic::set_hook(prev);
393 assert_eq!(r, Err(Denial { code: 0 }));
394 }
395
396 #[test]
397 fn test_allow_all_admits_and_allows() {
398 let info = ConnectionInfo::for_testing("127.0.0.1:1".parse().unwrap());
399 assert!(AllowAll.admit(&info, AdmitStage::Accept).is_ok());
400 let mut cell = GateCell {
401 gate: Arc::new(AllowAll),
402 ticket: Some(()),
403 };
404 let w = WriteCheck::new(info.id, Lane(0), 10, false, None);
405 assert!(cell.check(&w).is_ok());
406 cell.close(&info, CloseReason::SessionClosed);
407 assert!(cell.check(&w).is_err());
408 }
409
410 #[test]
411 fn test_refusal_code() {
412 assert_eq!(Refusal::Reset { code: 9 }.code(), 9);
413 }
414}