serve-net 0.6.1

The network service engine for Rust: listeners over net-io, ingress from direct clients, reverse proxies (PROXY protocol or trusted forwarded headers), Unix sockets, and FastCGI, a per-connection engine with a slot for any sans-IO protocol engine, admission, drain, and restarts without dropped connections.
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Errors: configuration errors and warnings, start-up and run-time errors,
//! and the reason every connection ended.

use core::fmt;

use crate::config::ProfileId;
use crate::net::CloseReason;

/// Which configuration rule an error or warning comes from.
///
/// Every rule is described in `docs/API.md` with what it refuses and how to
/// override it, if it can be overridden. `as_str` gives a stable name for
/// logs.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RuleId {
    /// A proxy or FastCGI listener on an unspecified or public address.
    PublicBind,
    /// Forwarded-header trust on a direct listener.
    ForwardedOnDirect,
    /// A FastCGI TCP listener with an empty trust list.
    FastCgiTrust,
    /// A trust entry of prefix length 0.
    TrustWildcard,
    /// A trust entry broader than /8 (IPv4) or /32 (IPv6).
    TrustTooBroad,
    /// Two client-address sources on one listener.
    TwoClientSources,
    /// A proxy listener with no trusted entry.
    TrustEmpty,
    /// A trust entry in text that did not parse.
    TrustParse,
    /// A Unix socket mode writable by others.
    WorldWritableSocket,
    /// A uid or gid allowlist where the platform has no peer credentials.
    PeerCredentialsUnavailable,
    /// An ingress that does not fit the listener's socket: `Unix` ingress on
    /// a TCP listener, or a TCP ingress on a Unix socket.
    IngressSource,
    /// Two listeners with one name.
    DuplicateName,
    /// A listener name outside 1 to 64 bytes of `[a-z0-9._-]`.
    BadName,
    /// `ProfileId(255)`, which is reserved.
    ProfileIdReserved,
    /// Profile ids not dense from 0, or repeated.
    ProfileGap,
    /// A listener naming a profile that does not exist.
    UnknownProfile,
    /// Deadlines in the wrong order.
    DeadlineOrder,
    /// A value outside its documented range.
    DeadlineRange,
    /// A connection or in-flight cap of 0.
    ZeroCap,
    /// Two listeners on one address or path.
    DuplicateBind,
    /// A driver this build or platform does not provide.
    DriverUnavailable,
    /// A reload that changes the workers.
    ReloadWorkers,
    /// A reload that changes what net-io fixed at bind: PROXY trust or TLS.
    ReloadListener,
    /// A drain deadline of 0 or above 1 h.
    DrainRange,
    /// ALPN engine choice on a listener without TLS.
    AlpnWithoutTls,
    /// TLS on a FastCGI listener.
    TlsOnFastCgi,
    /// `trust_scheme` or `trust_host` with no source that can carry them.
    SchemeTrustWithoutSource,
    /// A listener address that resolved to nothing.
    AddressResolve,
    /// A TLS listener with no TLS acceptor.
    TlsWithoutAcceptor,
    /// A field name that is not a token.
    BadHeaderName,
    /// Forwarded headers or FastCGI on a listener whose profile serves a custom family.
    IngressNeedsHttp,
    /// Lane reserves summing above 100%.
    ReserveOverflow,
    /// More than 64 listeners or 255 profiles.
    TooMany,
    /// Warning: a proxy listener left at `Scheme::Http` with `trust_scheme` off.
    DeclaredSchemeHttp,
    /// Warning: the minimum transfer rate is off.
    MinRateOff,
    /// Warning: `catch_service_panics` in a build that aborts on panic.
    PanicCatchInAbortBuild,
    /// Warning: `Offload` on the blocking driver behaves as `Inline`.
    OffloadOnBlocking,
    /// Warning: keep-alive idle under 5 s behind a proxy.
    ShortIdleBehindProxy,
    /// Warning: lockdown would refuse every profile (none is critical).
    LockdownWithoutCritical,
    /// Warning: no listener.
    NoListeners,
    /// `catch_service_panics` in a build where panics abort.
    CatchPanicsInAbortBuild,
}

impl RuleId {
    /// A stable snake_case name for logs.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            RuleId::PublicBind => "public_bind",
            RuleId::ForwardedOnDirect => "forwarded_on_direct",
            RuleId::FastCgiTrust => "fastcgi_trust",
            RuleId::TrustWildcard => "trust_wildcard",
            RuleId::TrustTooBroad => "trust_too_broad",
            RuleId::TwoClientSources => "two_client_sources",
            RuleId::TrustEmpty => "trust_empty",
            RuleId::TrustParse => "trust_parse",
            RuleId::WorldWritableSocket => "world_writable_socket",
            RuleId::PeerCredentialsUnavailable => "peer_credentials_unavailable",
            RuleId::IngressSource => "ingress_source",
            RuleId::DuplicateName => "duplicate_name",
            RuleId::BadName => "bad_name",
            RuleId::ProfileIdReserved => "profile_id_reserved",
            RuleId::ProfileGap => "profile_gap",
            RuleId::UnknownProfile => "unknown_profile",
            RuleId::DeadlineOrder => "deadline_order",
            RuleId::DeadlineRange => "deadline_range",
            RuleId::ZeroCap => "zero_cap",
            RuleId::DuplicateBind => "duplicate_bind",
            RuleId::DriverUnavailable => "driver_unavailable",
            RuleId::ReloadWorkers => "reload_workers",
            RuleId::ReloadListener => "reload_listener",
            RuleId::DrainRange => "drain_range",
            RuleId::AlpnWithoutTls => "alpn_without_tls",
            RuleId::TlsOnFastCgi => "tls_on_fastcgi",
            RuleId::SchemeTrustWithoutSource => "scheme_trust_without_source",
            RuleId::AddressResolve => "address_resolve",
            RuleId::TlsWithoutAcceptor => "tls_without_acceptor",
            RuleId::BadHeaderName => "bad_header_name",
            RuleId::IngressNeedsHttp => "ingress_needs_http",
            RuleId::ReserveOverflow => "reserve_overflow",
            RuleId::TooMany => "too_many",
            RuleId::DeclaredSchemeHttp => "declared_scheme_http",
            RuleId::MinRateOff => "min_rate_off",
            RuleId::PanicCatchInAbortBuild => "panic_catch_in_abort_build",
            RuleId::OffloadOnBlocking => "offload_on_blocking",
            RuleId::ShortIdleBehindProxy => "short_idle_behind_proxy",
            RuleId::LockdownWithoutCritical => "lockdown_without_critical",
            RuleId::NoListeners => "no_listeners",
            RuleId::CatchPanicsInAbortBuild => "catch_panics_in_abort_build",
        }
    }
}

impl fmt::Display for RuleId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What a configuration error or warning is about.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Subject {
    /// The server as a whole.
    Server,
    /// One listener, by name.
    Listener(String),
    /// One profile, by id.
    Profile(ProfileId),
}

impl fmt::Display for Subject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Subject::Server => f.write_str("server"),
            Subject::Listener(name) => write!(f, "listener {name}"),
            Subject::Profile(id) => write!(f, "profile {}", id.0),
        }
    }
}

/// One configuration error: the rule, its subject, what is wrong, and what to
/// change.
///
/// Messages and hints are fixed text: they never quote configuration values,
/// which may be secret, and never request data.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigError {
    /// The rule that refused the configuration.
    pub rule: RuleId,
    /// The server, listener, or profile it concerns.
    pub subject: Subject,
    /// What is wrong.
    pub message: &'static str,
    /// What to change.
    pub hint: &'static str,
}

impl ConfigError {
    pub(crate) fn new(
        rule: RuleId,
        subject: Subject,
        message: &'static str,
        hint: &'static str,
    ) -> Self {
        ConfigError {
            rule,
            subject,
            message,
            hint,
        }
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: {} ({}; rule {})",
            self.subject, self.message, self.hint, self.rule
        )
    }
}

/// A value that is allowed but questionable, kept by `Built::warnings`.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigWarning {
    /// The rule that noticed it.
    pub rule: RuleId,
    /// The server, listener, or profile it concerns.
    pub subject: Subject,
    /// What was noticed and why it matters.
    pub message: &'static str,
}

impl ConfigWarning {
    pub(crate) fn new(rule: RuleId, subject: Subject, message: &'static str) -> Self {
        ConfigWarning {
            rule,
            subject,
            message,
        }
    }
}

impl fmt::Display for ConfigWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {} (rule {})", self.subject, self.message, self.rule)
    }
}

/// Every configuration error found, never empty, sorted by subject.
///
/// The same configuration always gives the same errors in the same order, so
/// a configuration can be fixed in one pass.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigErrors {
    errors: Vec<ConfigError>,
}

impl ConfigErrors {
    /// Builds the list; `None` when there is no error.
    pub(crate) fn from_vec(mut errors: Vec<ConfigError>) -> Option<ConfigErrors> {
        if errors.is_empty() {
            return None;
        }
        // Stable: rules keep their check order within one subject.
        errors.sort_by(|a, b| a.subject.cmp(&b.subject));
        Some(ConfigErrors { errors })
    }

    /// The errors, sorted by subject.
    pub fn iter(&self) -> impl Iterator<Item = &ConfigError> {
        self.errors.iter()
    }

    /// The number of errors (at least 1).
    #[must_use]
    pub fn len(&self) -> usize {
        self.errors.len()
    }

    /// Always false: a `ConfigErrors` holds at least one error.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Whether any error comes from `rule`.
    #[must_use]
    pub fn has(&self, rule: RuleId) -> bool {
        self.errors.iter().any(|e| e.rule == rule)
    }
}

impl IntoIterator for ConfigErrors {
    type Item = ConfigError;
    type IntoIter = std::vec::IntoIter<ConfigError>;
    fn into_iter(self) -> Self::IntoIter {
        self.errors.into_iter()
    }
}

impl fmt::Display for ConfigErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = self.errors.len();
        write!(
            f,
            "{n} configuration error{}:",
            if n == 1 { "" } else { "s" }
        )?;
        for e in &self.errors {
            write!(f, "\n  {e}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ConfigErrors {}

/// A start-up or run-time error.
#[non_exhaustive]
#[derive(Debug)]
pub enum ServeError {
    /// The configuration was refused; every error is listed.
    Config(ConfigErrors),
    /// A listener could not be bound.
    Bind {
        /// The listener's name.
        listener: String,
        /// Why: in use, permission, or not on this host.
        source: net_io::NetError,
    },
    /// net-io could not start its workers or open the door.
    Start(net_io::NetError),
    /// An inherited socket is missing or of the wrong kind.
    Inherited {
        /// The listener's name.
        listener: String,
        /// What is wrong.
        reason: &'static str,
    },
    /// A handed-off socket is not of the kind the listener's ingress expects.
    HandOff {
        /// The listener's name.
        listener: String,
        /// What is wrong.
        reason: &'static str,
    },
    /// The operation needs a server that is not draining.
    Draining,
    /// A reload's configuration is invalid; nothing changed.
    Reload(ConfigErrors),
    /// A listener added by a reload could not be bound; nothing changed.
    ReloadBind {
        /// The listener's name.
        listener: String,
        /// Why.
        source: net_io::NetError,
    },
}

impl fmt::Display for ServeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ServeError::Config(errors) => write!(f, "{errors}"),
            ServeError::Bind { listener, source } => {
                write!(f, "listener `{listener}` could not be bound: {source}")
            }
            ServeError::Start(source) => write!(f, "the server could not start: {source}"),
            ServeError::Inherited { listener, reason } => {
                write!(f, "listener `{listener}`: {reason}")
            }
            ServeError::HandOff { listener, reason } => {
                write!(f, "listener `{listener}`: {reason}")
            }
            ServeError::Draining => {
                f.write_str("the server is draining; start a new server instead")
            }
            ServeError::Reload(errors) => {
                write!(f, "the reload changed nothing: {errors}")
            }
            ServeError::ReloadBind { listener, source } => {
                write!(
                    f,
                    "the reload changed nothing: listener `{listener}` could not be bound: {source}"
                )
            }
        }
    }
}

impl std::error::Error for ServeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ServeError::Config(errors) | ServeError::Reload(errors) => Some(errors),
            ServeError::Bind { source, .. }
            | ServeError::Start(source)
            | ServeError::ReloadBind { source, .. } => Some(source),
            ServeError::Inherited { .. } | ServeError::HandOff { .. } | ServeError::Draining => {
                None
            }
        }
    }
}

impl From<ConfigErrors> for ServeError {
    fn from(errors: ConfigErrors) -> Self {
        ServeError::Config(errors)
    }
}

/// Why a connection ended. Every connection ends with exactly one reason.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EndReason {
    /// net-io closed it: the peer, idle, a read or write timeout, a slow
    /// peer, a kill.
    Transport(CloseReason),
    /// No complete head within `head_timeout`.
    HeadTimeout,
    /// The body did not finish within `request_timeout`.
    RequestTimeout,
    /// A deferred reply did not come within `reply_timeout`.
    ReplyTimeout,
    /// The client or the protocol ended keep-alive.
    ClientClose,
    /// `max_requests` reached.
    RequestLimit,
    /// `max_age` reached.
    MaxAge,
    /// Finished after a drain started.
    Drained,
    /// The engine refused a malformed request.
    ProtocolError,
    /// A forwarded header or FastCGI parameter was missing or malformed, or
    /// the peer was not trusted.
    IngressRefused,
    /// A soft connection cap was full.
    CapacityRefused,
    /// Admission refused a request.
    Shed,
    /// `Checkpoint` denied a request.
    Denied,
    /// `Checkpoint` killed the connection.
    CheckpointKill,
    /// The service returned `Outcome::Close`.
    ServiceClosed,
    /// The service panicked.
    ServicePanic,
    /// A deferred reply's token was dropped without completing it.
    ReplyDropped,
    /// No engine for the negotiated protocol.
    NoEngine,
    /// The service refused the request in `head`.
    Refused,
}

impl EndReason {
    /// A stable snake_case name for logs.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            EndReason::Transport(_) => "transport",
            EndReason::HeadTimeout => "head_timeout",
            EndReason::RequestTimeout => "request_timeout",
            EndReason::ReplyTimeout => "reply_timeout",
            EndReason::ClientClose => "client_close",
            EndReason::RequestLimit => "request_limit",
            EndReason::MaxAge => "max_age",
            EndReason::Drained => "drained",
            EndReason::ProtocolError => "protocol_error",
            EndReason::IngressRefused => "ingress_refused",
            EndReason::CapacityRefused => "capacity_refused",
            EndReason::Shed => "shed",
            EndReason::Denied => "denied",
            EndReason::CheckpointKill => "checkpoint_kill",
            EndReason::ServiceClosed => "service_closed",
            EndReason::ServicePanic => "service_panic",
            EndReason::ReplyDropped => "reply_dropped",
            EndReason::NoEngine => "no_engine",
            EndReason::Refused => "refused",
        }
    }

    /// Whether the connection was closed with a reset rather than a graceful close.
    #[must_use]
    pub fn is_abortive(self) -> bool {
        match self {
            EndReason::CheckpointKill | EndReason::ServicePanic => true,
            EndReason::Transport(reason) => reason.is_abortive(),
            _ => false,
        }
    }
}

impl fmt::Display for EndReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn err(rule: RuleId, subject: Subject) -> ConfigError {
        ConfigError::new(rule, subject, "m", "h")
    }

    #[test]
    fn test_config_errors_empty_is_none() {
        assert!(ConfigErrors::from_vec(Vec::new()).is_none());
    }

    #[test]
    fn test_config_errors_sorted_by_subject_stable() {
        let errors = ConfigErrors::from_vec(vec![
            err(RuleId::BadName, Subject::Listener("b".into())),
            err(RuleId::ZeroCap, Subject::Server),
            err(RuleId::PublicBind, Subject::Listener("a".into())),
            err(RuleId::DuplicateName, Subject::Listener("b".into())),
        ])
        .unwrap();
        let rules: Vec<RuleId> = errors.iter().map(|e| e.rule).collect();
        assert_eq!(
            rules,
            [
                RuleId::ZeroCap,
                RuleId::PublicBind,
                RuleId::BadName,
                RuleId::DuplicateName
            ]
        );
        assert!(errors.has(RuleId::ZeroCap));
        assert!(!errors.has(RuleId::TrustEmpty));
        assert_eq!(errors.len(), 4);
    }

    #[test]
    fn test_config_errors_display_lists_every_error() {
        let errors = ConfigErrors::from_vec(vec![
            ConfigError::new(
                RuleId::ZeroCap,
                Subject::Server,
                "a cap is 0",
                "set it to 1 or more",
            ),
            ConfigError::new(
                RuleId::BadName,
                Subject::Listener("X".into()),
                "bad name",
                "use lowercase",
            ),
        ])
        .unwrap();
        let text = errors.to_string();
        assert!(text.starts_with("2 configuration errors:"));
        assert!(text.contains("server: a cap is 0 (set it to 1 or more; rule zero_cap)"));
        assert!(text.contains("listener X: bad name"));
    }

    #[test]
    fn test_serve_error_config_has_source() {
        let errors = ConfigErrors::from_vec(vec![err(RuleId::ZeroCap, Subject::Server)]).unwrap();
        let e = ServeError::from(errors);
        assert!(std::error::Error::source(&e).is_some());
        assert!(std::error::Error::source(&ServeError::Draining).is_none());
    }

    #[test]
    fn test_end_reason_names_unique() {
        let all = [
            EndReason::Transport(CloseReason::PeerClosed),
            EndReason::HeadTimeout,
            EndReason::RequestTimeout,
            EndReason::ReplyTimeout,
            EndReason::ClientClose,
            EndReason::RequestLimit,
            EndReason::MaxAge,
            EndReason::Drained,
            EndReason::ProtocolError,
            EndReason::IngressRefused,
            EndReason::CapacityRefused,
            EndReason::Shed,
            EndReason::Denied,
            EndReason::CheckpointKill,
            EndReason::ServiceClosed,
            EndReason::ServicePanic,
            EndReason::ReplyDropped,
            EndReason::NoEngine,
            EndReason::Refused,
        ];
        let mut names: Vec<&str> = all.iter().map(|r| r.as_str()).collect();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), all.len());
    }

    #[test]
    fn test_subject_display() {
        assert_eq!(Subject::Server.to_string(), "server");
        assert_eq!(Subject::Listener("web".into()).to_string(), "listener web");
        assert_eq!(Subject::Profile(ProfileId(1)).to_string(), "profile 1");
    }
}