tachyon-web 0.0.2

A fast, Axum-compatible async web framework with native TLS, HTTP/3, Tor (.onion), and I2P (.i2p) support
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
//! High-performance Web Server Engine supporting HTTP/1.1, HTTP/2, and HTTP/3.
//!
//! The `server` module provides the [`Server`] struct, which wraps a [`CompiledRouter`] and
//! dispatches incoming network streams for all supported HTTP versions.
//!
//! # Protocol support
//!
//! | Method | Protocol | Feature flag |
//! |---|---|---|
//! | [`serve_http`] | HTTP/1.1 plain TCP (+ HTTP/2 cleartext "h2c" with `http2`) | *(always)* |
//! | [`serve_https`] | HTTP/1.1 + HTTP/2 over TLS | `tls` |
//! | [`serve_https_config`] | Same but with custom `ServerConfig` | `tls` |
//! | [`serve_h3`] | HTTP/3 over QUIC | `http3` |
//! | [`start_all`] | All of the above via PEM cert/key strings | `cert-gen` |
//! | [`serve_all_acme`] | All of the above, certs managed by Let's Encrypt | `lets-encrypt` |
//! | [`serve_tor`] | HTTP/1.1 (+ h2c) over a native Tor `.onion` hidden service | `tor` |
//! | [`serve_i2p`] | HTTP/1.1 (+ h2c) over a native I2P `.b32.i2p` eepsite ([⚠️ breaks `forbid(unsafe_code)`](i2p)) | `i2p` |
//!
//! [`serve_http`]: Server::serve_http
//! [`serve_https`]: Server::serve_https
//! [`serve_https_config`]: Server::serve_https_config
//! [`serve_h3`]: Server::serve_h3
//! [`start_all`]: Server::start_all
//! [`serve_all_acme`]: Server::serve_all_acme
//! [`serve_tor`]: Server::serve_tor
//! [`serve_i2p`]: Server::serve_i2p
//! [`CompiledRouter`]: crate::routing::CompiledRouter
//!
//! # Publishing over more than one transport at once
//!
//! Each `serve_*` method above consumes its `Server` and blocks for that one transport's
//! lifetime — the right building block for a single-transport deployment. To publish the same
//! app over **several** transports at once (e.g. clearnet HTTPS *and* a `.onion` mirror *and*
//! a `.i2p` mirror, all from one process), prefer [`MultiServer`] over hand-rolling
//! `tokio::spawn` + `tokio::select!` around the individual `serve_*` calls yourself — it owns
//! exactly that boilerplate:
//!
//! ```rust,no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//! use tachyon_web::{Router, Server, get};
//!
//! let app: Router = Router::new().route("/", get(|| async { "hi" }));
//! let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
//!
//! Server::new(app)
//!     .with_http(listener)
//!     // .with_onion(onion_config)   // requires the `tor` feature
//!     // .with_i2p(i2p_config)       // requires the `i2p` feature
//!     .serve()
//!     .await?;
//! # Ok(())
//! # }
//! ```

#[cfg(any(feature = "tor", feature = "i2p"))]
pub(crate) mod conn;
#[cfg(feature = "http3")]
mod h3;
mod http;
#[cfg(feature = "i2p")]
pub mod i2p;
mod multi;
#[cfg(feature = "tor")]
pub mod tor;

pub use multi::MultiServer;

use crate::routing::CompiledRouter;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;

#[cfg(feature = "tls")]
use crate::http::response::Body;
#[cfg(feature = "tls")]
use hyper::service::service_fn;
#[cfg(feature = "tls")]
use hyper::{Request, Response};
#[cfg(any(feature = "cert-gen", feature = "lets-encrypt", feature = "http3"))]
use tokio_rustls::TlsAcceptor;

/// Default read timeout for both plaintext and TLS connections.
pub(crate) const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// Default handshake timeout for TLS connections.
#[cfg(feature = "tls")]
pub(crate) const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
/// How long [`Server::serve_all_acme`] waits for the first certificate to be
/// cached or provisioned before starting the TLS listener regardless.
#[cfg(feature = "lets-encrypt")]
const FIRST_CERT_TIMEOUT: Duration = Duration::from_secs(60);

thread_local! {
    pub(crate) static IS_LOCAL_WORKER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Samples a delay uniformly from `[min, max)` for [`Server::response_jitter`].
///
/// Not a CSPRNG — this only needs enough variance to blunt naive response-time
/// correlation, not to resist an adversary who can influence the seed, so a
/// `RandomState` hasher (itself seeded from the OS's own random source at
/// construction) reseeded with the current time is sufficient without pulling in a
/// dedicated `rand` dependency for one call site.
pub(crate) fn jittered_delay(min: Duration, max: Duration) -> Duration {
    use std::hash::{BuildHasher, Hasher};

    if max <= min {
        return min;
    }
    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
    let now_nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    hasher.write_u128(now_nanos);
    let span_nanos = max.checked_sub(min).unwrap_or(max).as_nanos().max(1);
    let offset_nanos = (u128::from(hasher.finish()) % span_nanos).min(u128::from(u64::MAX));
    min + Duration::from_nanos(u64::try_from(offset_nanos).unwrap_or(u64::MAX))
}

fn bind_reuseport(addr: std::net::SocketAddr) -> Result<std::net::TcpListener, std::io::Error> {
    use socket2::{Domain, Protocol, Socket, Type};
    let domain = Domain::for_address(addr);
    let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
    socket.set_reuse_address(true)?;
    #[cfg(unix)]
    {
        socket.set_reuse_port(true)?;
    }
    socket.bind(&addr.into())?;
    socket.set_nonblocking(true)?;
    socket.listen(4096)?;
    Ok(std::net::TcpListener::from(socket))
}

async fn run_worker_pool<S, F, Fut>(
    server: Server<S>,
    addr: std::net::SocketAddr,
    redirect_info: Option<(std::net::SocketAddr, u16)>,
    serve_fn: F,
) -> Result<(), std::io::Error>
where
    S: Clone + Send + Sync + 'static,
    F: Fn(Server<S>, TcpListener) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), std::io::Error>> + Send + 'static,
{
    let cores = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
    let core_ids = core_affinity::get_core_ids().unwrap_or_default();
    let mut handles = Vec::new();
    let server = Arc::new(server);
    let serve_fn = Arc::new(serve_fn);
    // Each worker thread reports whether it managed to bind its listener, so
    // that a totally unbindable address (e.g. permission denied, or already
    // in use on every core) produces a real `Err` instead of hanging forever
    // on the `pending()` below with only a log line to show for it.
    let (bind_tx, bind_rx) = std::sync::mpsc::channel::<Result<(), std::io::Error>>();

    for i in 0..cores {
        let server = server.clone();
        let serve_fn = serve_fn.clone();
        let core_id = core_ids.get(i).copied();
        let bind_tx = bind_tx.clone();
        let handle = std::thread::Builder::new()
            .name(format!("tachyon-worker-{i}"))
            .stack_size(512 * 1024)
            .spawn(move || {
                if let Some(id) = core_id {
                    let _ = core_affinity::set_for_current(id);
                }

                let Ok(rt) = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                else {
                    tracing::error!("Failed to build Tokio runtime for worker thread");
                    return;
                };

                let local = tokio::task::LocalSet::new();
                local.block_on(&rt, async move {
                    IS_LOCAL_WORKER.with(|flag| flag.set(true));

                    // Only used to bind the HTTP->HTTPS redirect listener, which only
                    // exists when TLS is enabled — kept alive here so the parameter
                    // isn't flagged as unused in non-`tls` builds.
                    #[cfg(not(feature = "tls"))]
                    let _ = &redirect_info;

                    #[cfg(feature = "tls")]
                    if let Some((r_addr, https_port)) = redirect_info {
                        let r_listener_res = bind_reuseport(r_addr).and_then(TcpListener::from_std);
                        match r_listener_res {
                            Ok(l) => {
                                tokio::task::spawn_local(async move {
                                    serve_http_redirect_and_challenges(l, https_port).await;
                                });
                            }
                            Err(e) => {
                                tracing::error!("Worker redirect bind error: {e}");
                            }
                        }
                    }

                    let listener_res = bind_reuseport(addr).and_then(TcpListener::from_std);
                    let listener = match listener_res {
                        Ok(l) => {
                            let _ = bind_tx.send(Ok(()));
                            l
                        }
                        Err(e) => {
                            tracing::error!("Worker bind error: {e}");
                            let _ = bind_tx.send(Err(e));
                            return;
                        }
                    };

                    let server_clone = (*server).clone();

                    let _ = serve_fn(server_clone, listener).await;
                });
            })?;
        handles.push(handle);
    }
    drop(bind_tx);

    let bind_results = tokio::task::spawn_blocking(move || {
        (0..cores)
            .filter_map(|_| bind_rx.recv().ok())
            .collect::<Vec<_>>()
    })
    .await
    .unwrap_or_default();
    let bound = bind_results.iter().filter(|r| r.is_ok()).count();
    if bound == 0 {
        return Err(bind_results
            .into_iter()
            .find_map(std::result::Result::err)
            .unwrap_or_else(|| {
                std::io::Error::other("all worker threads failed to bind their listener")
            }));
    }
    if bound < cores {
        tracing::warn!(
            "Only {bound}/{cores} worker threads bound successfully; running in a degraded state"
        );
    }

    let _ = handles;
    std::future::pending::<()>().await;
    Ok(())
}

// ─── Server ──────────────────────────────────────────────────────────────────

/// Main server configuration and runner.
///
/// Wraps a [`CompiledRouter`] and provides multiple `serve_*` methods for different
/// transport protocols. The server is cheaply cloneable via `Arc` internally.
///
/// # Example
///
/// ```rust,no_run
/// use tachyon_web::{Router, Server, get};
/// use tokio::net::TcpListener;
///
/// async fn hello() -> &'static str { "hello" }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///     let app = Router::new().route("/", get(hello));
///     let listener = TcpListener::bind("0.0.0.0:8080").await?;
///     Server::new(app).serve_http(listener).await?;
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct Server<S> {
    pub(crate) router: CompiledRouter<S>,
    /// Maximum permitted request body size in bytes (default: 2 MiB, matching
    /// Axum's `DefaultBodyLimit` default).
    pub max_body_size: usize,
    /// Maximum number of concurrent active TCP connections **per worker thread**.
    ///
    /// Tachyon runs one worker (with its own `SO_REUSEPORT` listener and connection
    /// semaphore) per CPU core, so the effective process-wide ceiling is
    /// `max_connections × number of cores`, not a single global cap. Size this
    /// accordingly if you're relying on it for downstream resource planning (e.g.
    /// a connection-pooled database sized to the server's max concurrency).
    ///
    /// This per-core sharding applies to [`serve_http`] and [`serve_https`]
    /// (and anything built on them, like [`serve_all_acme`]). HTTP/3
    /// ([`serve_h3`]) runs a single QUIC endpoint with its own connection
    /// semaphore, not sharded across the worker pool — for H3 traffic the
    /// effective ceiling is `max_connections` alone.
    ///
    /// [`serve_http`]: Server::serve_http
    /// [`serve_https`]: Server::serve_https
    /// [`serve_all_acme`]: Server::serve_all_acme
    /// [`serve_h3`]: Server::serve_h3
    ///
    /// Default: 25,600 — matching `actix-server`'s own per-worker
    /// `max_concurrent_connections`.
    pub max_connections: usize,
    /// Crypto/TLS policy shared across every listener this `Server` runs — see
    /// [`Server::tls_policy`]. `None` means each listener falls back to
    /// [`TlsPolicy::hardened`](crate::tls::TlsPolicy::hardened).
    #[cfg(feature = "tls")]
    pub(crate) tls_policy: Option<crate::tls::TlsPolicy>,
    /// Random per-response delay range added before every response is returned — see
    /// [`Server::response_jitter`]. `None` (the default) adds no delay.
    pub(crate) response_jitter: Option<(Duration, Duration)>,
}

impl<S> Clone for Server<S>
where
    S: Clone,
{
    fn clone(&self) -> Self {
        Self {
            router: self.router.clone(),
            max_body_size: self.max_body_size,
            max_connections: self.max_connections,
            #[cfg(feature = "tls")]
            tls_policy: self.tls_policy.clone(),
            response_jitter: self.response_jitter,
        }
    }
}

impl Server<()> {
    /// Creates a new `Server` with default settings and the given router.
    ///
    /// # Panics
    /// Panics if router compilation fails (e.g. a duplicate route was registered).
    #[must_use]
    #[allow(clippy::expect_used)]
    pub fn new(router: crate::routing::Router<()>) -> Self {
        let compiled = router.compile().expect("Router compilation failed");
        Self {
            router: compiled,
            max_body_size: 2 * 1024 * 1024, // 2 MiB (matches Axum's `DefaultBodyLimit` default)
            max_connections: 25_600,
            #[cfg(feature = "tls")]
            tls_policy: None,
            response_jitter: None,
        }
    }
}

impl<S> Server<S>
where
    S: Clone + Send + Sync + 'static,
{
    /// Overrides the maximum request body size (in bytes).
    ///
    /// Requests whose body exceeds this limit are rejected with `413 Content Too Large`
    /// before the body bytes are fully buffered. The default is **2 MiB**, matching
    /// Axum's `DefaultBodyLimit` default.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use tachyon_web::{Router, Server};
    /// # let router = Router::new();
    /// let server = Server::new(router).max_body_size(64 * 1024 * 1024); // 64 MiB
    /// ```
    #[must_use]
    pub const fn max_body_size(mut self, size: usize) -> Self {
        self.max_body_size = size;
        self
    }

    /// Overrides the maximum number of concurrent connections **per worker thread**
    /// (default: 25,600 — see [`Server::max_connections`] for why this isn't a
    /// single process-wide cap).
    #[must_use]
    pub const fn max_connections(mut self, limit: usize) -> Self {
        self.max_connections = limit;
        self
    }

    /// Adds a random delay, uniformly sampled from `[min, max)`, before every response this
    /// `Server` returns — on every transport it serves (clearnet, `.onion`, `.i2p` alike, since
    /// they all funnel through the same response path).
    ///
    /// Off by default. This exists to blunt naive **response-time correlation**: if you run the
    /// same app on both clearnet and a `.onion`/`.i2p` mirror (e.g. via [`MultiServer`]), an
    /// observer positioned to time both could otherwise try to match requests between them by
    /// how long the handler took to respond. Jitter alone does not make correlation impossible —
    /// it raises the number of samples an observer needs, nothing more — so treat it as one
    /// layer among several (network-level timing is a much stronger signal than this addresses),
    /// not a complete mitigation.
    ///
    /// `min == max` (or `max <= min`) always waits exactly `min` — use this for a fixed
    /// per-response delay instead of a random range.
    #[must_use]
    pub const fn response_jitter(mut self, min: Duration, max: Duration) -> Self {
        self.response_jitter = Some((min, max));
        self
    }

    /// Sets a custom `rustls::crypto::CryptoProvider` to be used for TLS operations.
    ///
    /// This overrides the default provider (which uses `aws-lc-rs` with customized Kex and AEAD).
    /// Shorthand for `.tls_policy(TlsPolicy::with_provider(provider))` — use
    /// [`tls_policy`](Self::tls_policy) directly if you also want to restrict protocol
    /// versions (e.g. TLS 1.3-only) or install this provider process-wide for arti's Tor
    /// relay connections.
    #[cfg(feature = "tls")]
    #[must_use]
    pub fn crypto_provider(self, provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
        self.tls_policy(crate::tls::TlsPolicy::with_provider(provider))
    }

    /// Sets the crypto/TLS policy shared by every listener this `Server` runs: clearnet HTTPS
    /// (static cert or Let's Encrypt), the onion `.onion` HTTPS termination, and the I2P
    /// eepsite's optional TLS layer. All three derive their `rustls::ServerConfig` (including
    /// self-signed certs) from the same [`TlsPolicy`](crate::tls::TlsPolicy) instead of each
    /// reconstructing their own defaults.
    ///
    /// Defaults to [`TlsPolicy::hardened`](crate::tls::TlsPolicy::hardened) if never called.
    ///
    /// See [`TlsPolicy`](crate::tls::TlsPolicy)'s docs for how this interacts with Tor's
    /// relay/channel TLS layer (a separate concern from HTTPS termination).
    #[cfg(feature = "tls")]
    #[must_use]
    pub fn tls_policy(mut self, policy: crate::tls::TlsPolicy) -> Self {
        self.tls_policy = Some(policy);
        self
    }

    /// Returns the effective [`TlsPolicy`](crate::tls::TlsPolicy) for this server: the one set
    /// via [`tls_policy`](Self::tls_policy)/[`crypto_provider`](Self::crypto_provider), or
    /// [`TlsPolicy::hardened`](crate::tls::TlsPolicy::hardened) if neither was called.
    ///
    /// Only consumed by the entry points that actually build a `rustls::ServerConfig`
    /// themselves — or, for `tor`, that install this policy's provider as rustls's
    /// process-wide default before bootstrapping (see `TlsPolicy`'s docs): `start_all`/
    /// `start_all_inner` (`cert-gen`), `serve_all_acme` (`lets-encrypt`, which implies
    /// `cert-gen`), `Server::serve_tor`/`serve_onion` (`tor` + `tls`, for the process-wide
    /// install — the plaintext-only `_with_client` variants never call this since they don't
    /// own the bootstrap), and the onion/i2p self-signed-cert paths in `server/tor.rs`/
    /// `server/i2p.rs` (both require `cert-gen`, already covered by that disjunct — a
    /// caller-supplied `OnionTls::Custom`/`I2pTls::Custom` config, needing only `tls`, doesn't
    /// call this at all). Gated the same way so builds that don't actually reach any of these
    /// paths don't trip `-D dead-code`.
    #[cfg(any(
        feature = "cert-gen",
        feature = "lets-encrypt",
        all(feature = "tor", feature = "tls"),
    ))]
    pub(crate) fn effective_tls_policy(&self) -> crate::tls::TlsPolicy {
        self.tls_policy.clone().unwrap_or_default()
    }

    /// Begins publishing this app over **multiple transports at once** — see
    /// [`MultiServer`] and the [module docs](self#publishing-over-more-than-one-transport-at-once).
    ///
    /// Adds a plaintext clearnet HTTP transport bound to `listener`; chain more `.with_*` calls
    /// (`.with_https`/`.with_h3`/`.with_onion`/`.with_i2p`) to add further transports, then
    /// finish with `.serve().await`.
    pub fn with_http(self, listener: TcpListener) -> MultiServer<S> {
        MultiServer::new(self).with_http(listener)
    }

    /// Begins publishing this app over **multiple transports at once** — see
    /// [`MultiServer`] and the [module docs](self#publishing-over-more-than-one-transport-at-once).
    ///
    /// Adds a clearnet HTTPS transport bound to `listener`, terminated with `config`. Requires
    /// the `tls` feature.
    #[cfg(feature = "tls")]
    pub fn with_https(self, listener: TcpListener, config: rustls::ServerConfig) -> MultiServer<S> {
        MultiServer::new(self).with_https(listener, config)
    }

    /// Begins publishing this app over **multiple transports at once** — see
    /// [`MultiServer`] and the [module docs](self#publishing-over-more-than-one-transport-at-once).
    ///
    /// Adds an HTTP/3-over-QUIC transport. Requires the `http3` feature.
    #[cfg(feature = "http3")]
    pub fn with_h3(self, quic_server: s2n_quic::Server) -> MultiServer<S> {
        MultiServer::new(self).with_h3(quic_server)
    }

    /// Begins publishing this app over **multiple transports at once** — see
    /// [`MultiServer`] and the [module docs](self#publishing-over-more-than-one-transport-at-once).
    ///
    /// Adds a Tor `.onion` hidden-service transport. Requires the `tor` feature.
    #[cfg(feature = "tor")]
    pub fn with_onion(self, config: tor::OnionConfig) -> MultiServer<S> {
        MultiServer::new(self).with_onion(config)
    }

    /// Begins publishing this app over **multiple transports at once** — see
    /// [`MultiServer`] and the [module docs](self#publishing-over-more-than-one-transport-at-once).
    ///
    /// Adds an I2P `.b32.i2p` eepsite transport. Requires the `i2p` feature
    /// ([⚠️ breaks `forbid(unsafe_code)`](i2p)).
    #[cfg(feature = "i2p")]
    pub fn with_i2p(self, config: i2p::I2pConfig) -> MultiServer<S> {
        MultiServer::new(self).with_i2p(config)
    }

    /// Starts a pure plaintext HTTP server on a parsed `SocketAddr`.
    ///
    /// # Errors
    ///
    /// Returns an error if the server fails to run.
    pub async fn start_http_addr(self, addr: std::net::SocketAddr) -> Result<(), std::io::Error> {
        run_worker_pool(self, addr, None, |server, listener| async move {
            server.serve_http(listener).await
        })
        .await
    }

    /// Starts a pure plaintext HTTP server.
    ///
    /// # Arguments
    /// - `http_addr`: The address to bind (e.g., `"0.0.0.0:80"`).
    ///
    /// # Errors
    ///
    /// Returns an error if parsing the bind address fails or the server fails to run.
    pub async fn start_http(self, http_addr: &str) -> Result<(), std::io::Error> {
        let addr: std::net::SocketAddr = http_addr
            .parse()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        self.start_http_addr(addr).await
    }

    /// Starts a pure HTTPS server (HTTP/1.1 and HTTP/2 over TLS) using a custom `rustls::ServerConfig`.
    ///
    /// This provides advanced control for users who want to configure TLS themselves,
    /// without relying on `cert-gen` or Let's Encrypt automation.
    ///
    /// # Arguments
    /// - `tls_addr`: The address to bind for TLS (e.g., `"0.0.0.0:443"`).
    /// - `config`: A configured `rustls::ServerConfig`.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing the bind address fails or the server fails to run.
    #[cfg(feature = "tls")]
    pub async fn start_https_with_config_addr(
        self,
        addr: std::net::SocketAddr,
        config: rustls::ServerConfig,
    ) -> Result<(), std::io::Error> {
        let config = Arc::new(config);
        run_worker_pool(self, addr, None, move |server, listener| {
            let config = config.clone();
            async move { server.serve_https_config(listener, (*config).clone()).await }
        })
        .await
    }

    /// Starts a pure HTTPS server (HTTP/1.1 and HTTP/2 over TLS) using a custom `rustls::ServerConfig`.
    ///
    /// This provides advanced control for users who want to configure TLS themselves,
    /// without relying on `cert-gen` or Let's Encrypt automation.
    ///
    /// # Arguments
    /// - `tls_addr`: The address to bind for TLS (e.g., `"0.0.0.0:443"`).
    /// - `config`: A configured `rustls::ServerConfig`.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing the bind address fails or the server fails to run.
    #[cfg(feature = "tls")]
    pub async fn start_https_with_config(
        self,
        tls_addr: &str,
        config: rustls::ServerConfig,
    ) -> Result<(), std::io::Error> {
        let addr: std::net::SocketAddr = tls_addr
            .parse()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        self.start_https_with_config_addr(addr, config).await
    }

    /// Starts HTTPS (HTTP/1.1 + HTTP/2 over TLS) and HTTP/3 (QUIC) using a custom `rustls::ServerConfig`.
    ///
    /// This provides advanced control for users who want to configure TLS themselves,
    /// without relying on `cert-gen` or Let's Encrypt automation. Both listeners will bind
    /// to the provided `tls_addr` (TCP for HTTPS and UDP for HTTP/3).
    ///
    /// # Arguments
    /// - `tls_addr`: The address to bind for TCP and UDP (e.g., `"0.0.0.0:443"`).
    /// - `config`: A configured `rustls::ServerConfig`.
    ///
    /// # Errors
    ///
    /// Returns an error if FIPS compliance enforcement, binding, or server initialization fails.
    #[cfg(all(feature = "tls", feature = "http3"))]
    pub async fn start_https_and_h3_with_config(
        self,
        tls_addr: &str,
        mut config: rustls::ServerConfig,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        enforce_fips_compliance()?;

        // Ensure ALPN includes HTTP/3 and standard HTTP/2 / HTTP/1.1
        config.alpn_protocols = alpn_protocols(true);
        let config = Arc::new(config);

        // Start HTTP/3 QUIC Server
        let quic_tls = s2n_quic::provider::tls::rustls::Server::from(config.clone());
        let quic_limits = s2n_quic::provider::limits::Limits::new()
            // 1 MB flow-control windows match H/2 settings and saturate LAN pipes.
            .with_data_window(1_048_576)?
            .with_bidirectional_local_data_window(1_048_576)?
            .with_bidirectional_remote_data_window(1_048_576)?
            // Tuning: 100ms is a safe and standard default initial RTT for public internet clients.
            .with_initial_round_trip_time(Duration::from_millis(100))?
            // More simultaneous streams per connection.
            .with_max_open_remote_bidirectional_streams(4096)?
            // Keep ACK overhead low: ACK every 4th packet (default is every 2nd).
            .with_ack_elicitation_interval(4)?
            // Disable active migration for server-side benchmarks (saves state tracking).
            .with_active_connection_migration(false)?
            // Reduce connection-ID slots (fewer is fine for 0-RTT / stationary peers).
            .with_max_active_connection_ids(2)?
            // Aggressive handshake timeout: reject slow clients quickly.
            .with_max_handshake_duration(Duration::from_secs(5))?;
        let quic_server = s2n_quic::Server::builder()
            .with_tls(quic_tls)?
            .with_limits(quic_limits)?
            .with_io(tls_addr)?
            .start()?;

        let server_h3 = self.clone();
        drop(tokio::spawn(async move {
            let _ = server_h3.serve_h3(quic_server).await;
        }));

        // Start HTTPS Server
        let addr: std::net::SocketAddr = tls_addr
            .parse()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        let tls_acceptor = TlsAcceptor::from(config);
        let tls_acceptor = Arc::new(tls_acceptor);
        run_worker_pool(self, addr, None, move |server, listener| {
            let tls_acceptor = tls_acceptor.clone();
            async move { server.serve_https(listener, (*tls_acceptor).clone()).await }
        })
        .await?;

        Ok(())
    }

    /// Starts the server across **all enabled protocols simultaneously** using
    /// pre-loaded PEM certificate and key strings.
    ///
    /// This is a convenience wrapper that sets up:
    /// - **HTTP → HTTPS redirect** on `cleartext_addr` (if provided), with ACME HTTP-01
    ///   challenge pass-through so Let's Encrypt can validate the domain even while
    ///   this server is running.
    /// - **HTTP/3** (QUIC) on `tls_addr` (if the `http3` feature is enabled).
    /// - **HTTPS** (HTTP/1.1 + HTTP/2 over TLS) on `tls_addr`, which blocks
    ///   the current task.
    ///
    /// # Arguments
    /// - `tls_addr`: The address to bind for TLS (e.g., `"0.0.0.0:443"`).
    /// - `cleartext_addr`: Optional plaintext HTTP address for the redirect listener
    ///   (e.g., `Some("0.0.0.0:80")`). Pass `None` if you manage HTTP elsewhere.
    /// - `cert_pem`: PEM-encoded certificate chain (leaf + intermediates).
    /// - `key_pem`: PEM-encoded ECDSA or RSA private key.
    ///
    /// # Errors
    /// Returns an error if address binding, TLS configuration, or certificate parsing fails.
    #[cfg(feature = "cert-gen")]
    pub async fn start_all(
        self,
        tls_addr: &str,
        cleartext_addr: Option<&str>,
        cert_pem: String,
        key_pem: String,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.start_all_inner(tls_addr, cleartext_addr, cert_pem, key_pem)
            .await
    }

    /// Starts the server with **automatic Let's Encrypt certificate management**.
    ///
    /// This is the simplest way to deploy a production HTTPS server with Tachyon.
    /// It combines [`AcmeManager`] (certificate issuance and renewal) with [`start_all`]
    /// (multi-protocol serving) into a single call.
    ///
    /// # What this does
    ///
    /// 1. Creates an [`AcmeManager`] for the given `domains` and `email`.
    /// 2. Starts the ACME background renewal loop.
    /// 3. Binds an HTTP listener on `cleartext_addr` that:
    ///    - Serves ACME HTTP-01 challenge responses (required for cert issuance).
    ///    - Redirects all other requests to HTTPS with `308 Permanent Redirect`.
    /// 4. Waits (up to 30s) for the first certificate to be cached or
    ///    provisioned, then starts the TLS listener regardless of whether
    ///    that wait timed out.
    /// 5. Optionally starts HTTP/3 QUIC listener (if the `http3` feature is enabled).
    ///
    /// # Arguments
    /// - `tls_addr`: Address to bind for HTTPS (e.g., `"0.0.0.0:443"`).
    /// - `cleartext_addr`: Address to bind for HTTP and ACME challenges (e.g., `"0.0.0.0:80"`).
    ///   **Port 80 must be publicly reachable** for Let's Encrypt HTTP-01 challenges to work.
    /// - `domains`: Domain names to include in the certificate (must all resolve to this server).
    /// - `email`: Contact email for Let's Encrypt account registration and expiry notices.
    /// - `cache_dir`: Directory to store credentials and the certificate on disk.
    ///   Must be writable. Survives server restarts — this prevents hitting rate limits.
    /// - `staging`: If `true`, uses the Let's Encrypt **staging** environment.
    ///   Recommended for testing; staging issues untrusted certs but has much higher rate limits.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use tachyon_web::{Router, Server, get};
    ///
    /// async fn hello() -> &'static str { "Hello, HTTPS World!" }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    ///     #[cfg(feature = "lets-encrypt")]
    ///     {
    ///         let app = Router::new().route("/", get(hello));
    ///
    ///         Server::new(app)
    ///             .serve_all_acme(
    ///                 "0.0.0.0:443",
    ///                 "0.0.0.0:80",
    ///                 vec!["example.com".to_string(), "www.example.com".to_string()],
    ///                 "admin@example.com".to_string(),
    ///                 "/var/cache/tachyon/certs",
    ///                 false,  // false = production Let's Encrypt
    ///             )
    ///             .await?;
    ///     }
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    /// Returns an error if:
    /// - The HTTP or HTTPS addresses cannot be bound.
    /// - The ACME account cannot be created or loaded.
    /// - Certificate provisioning fails (after exhausting retries).
    ///
    /// [`AcmeManager`]: crate::tls::acme::AcmeManager
    /// [`start_all`]: Server::start_all
    #[cfg(feature = "lets-encrypt")]
    pub async fn serve_all_acme(
        self,
        tls_addr: &str,
        cleartext_addr: &str,
        domains: Vec<String>,
        email: String,
        cache_dir: impl Into<std::path::PathBuf>,
        staging: bool,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use crate::tls::acme::AcmeManager;
        enforce_fips_compliance()?;

        let acme = AcmeManager::new(cache_dir, domains, email, staging);
        let resolver = acme.resolver();

        // Start the background renewal loop before attempting to serve.
        acme.start();

        // Give the renewal loop a bounded window to load a cached cert or
        // provision a fresh one before the TLS listener starts accepting —
        // otherwise every connection that lands before the first cert is
        // ready fails its handshake. If provisioning is still in flight after
        // the timeout (e.g. a slow ACME order), proceed anyway rather than
        // hang startup forever; those early connections will fail until the
        // cert lands, same as today, but the common case (cached or
        // fast-issued cert) now actually gets served from the start.
        let wait_start = tokio::time::Instant::now();
        while !resolver.has_certificate() {
            if wait_start.elapsed() >= FIRST_CERT_TIMEOUT {
                tracing::warn!(
                    "[acme] No certificate ready after {:?}; starting TLS listener anyway — \
                     connections will fail until provisioning completes",
                    FIRST_CERT_TIMEOUT
                );
                break;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }

        // Build the TLS config backed by the ACME hot-swap resolver, sharing the same
        // crypto/TLS policy as the onion/i2p listeners (see `Server::tls_policy`).
        let policy = self.effective_tls_policy();
        let mut tls_config = rustls::ServerConfig::builder_with_provider(policy.provider())
            .with_protocol_versions(policy.versions())
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("TLS version configuration failed: {e}"),
                )
            })?
            .with_no_client_auth()
            .with_cert_resolver(resolver);

        #[cfg(feature = "http3")]
        {
            tls_config.alpn_protocols = alpn_protocols(true);
        }
        #[cfg(not(feature = "http3"))]
        {
            tls_config.alpn_protocols = alpn_protocols(false);
        }

        let tls_config = Arc::new(tls_config);
        let tls_acceptor = TlsAcceptor::from(tls_config.clone());

        #[cfg(feature = "http3")]
        {
            let quic_tls = s2n_quic::provider::tls::rustls::Server::from(tls_config);
            let quic_limits = s2n_quic::provider::limits::Limits::new()
                .with_data_window(1_048_576)?
                .with_bidirectional_local_data_window(1_048_576)?
                .with_bidirectional_remote_data_window(1_048_576)?
                .with_initial_round_trip_time(Duration::from_millis(100))?
                .with_max_open_remote_bidirectional_streams(4096)?
                .with_ack_elicitation_interval(4)?
                .with_active_connection_migration(false)?
                .with_max_active_connection_ids(2)?
                .with_max_handshake_duration(Duration::from_secs(5))?;
            let quic_server = s2n_quic::Server::builder()
                .with_tls(quic_tls)?
                .with_limits(quic_limits)?
                .with_io(tls_addr)?
                .start()?;

            let server_h3 = self.clone();
            drop(tokio::spawn(async move {
                let _ = server_h3.serve_h3(quic_server).await;
            }));
        }

        // Bind the HTTPS listener and serve (blocks the calling task).
        let addr: std::net::SocketAddr = tls_addr
            .parse()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        let tls_acceptor = Arc::new(tls_acceptor);
        let redirect_addr: std::net::SocketAddr = cleartext_addr
            .parse()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        let https_port = parse_port(tls_addr, 443);
        run_worker_pool(
            self,
            addr,
            Some((redirect_addr, https_port)),
            move |server, listener| {
                let tls_acceptor = tls_acceptor.clone();
                async move { server.serve_https(listener, (*tls_acceptor).clone()).await }
            },
        )
        .await?;

        Ok(())
    }

    /// Internal: shared setup logic for `start_all`.
    ///
    /// # Errors
    /// Returns an error if address binding, TLS configuration, or certificate parsing fails.
    #[cfg(feature = "cert-gen")]
    #[allow(clippy::too_many_lines)]
    async fn start_all_inner(
        self,
        tls_addr: &str,
        cleartext_addr: Option<&str>,
        cert_pem: String,
        key_pem: String,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use rustls::pki_types::{CertificateDer, PrivateKeyDer};
        use rustls_pemfile::{certs, private_key};
        enforce_fips_compliance()?;

        let mut cert_reader = std::io::BufReader::new(cert_pem.as_bytes());
        let cert_chain: Vec<CertificateDer<'static>> = certs(&mut cert_reader)
            .filter_map(std::result::Result::ok)
            .collect();

        let mut key_reader = std::io::BufReader::new(key_pem.as_bytes());
        let key_der: PrivateKeyDer<'static> = private_key(&mut key_reader)
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Failed to read private key: {e}"),
                )
            })?
            .ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "No private key found in PEM",
                )
            })?;

        // Shares the same crypto/TLS policy as the onion/i2p listeners — see
        // `Server::tls_policy`. Call `.tls_policy(TlsPolicy::hardened().tls13_only())` (or a
        // fully custom `TlsPolicy`) for stricter version pinning than the default (TLS 1.3
        // and 1.2 both offered).
        let policy = self.effective_tls_policy();
        let mut tls_config = rustls::ServerConfig::builder_with_provider(policy.provider())
            .with_protocol_versions(policy.versions())
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Failed to configure TLS protocol versions: {e}"),
                )
            })?
            .with_no_client_auth()
            .with_single_cert(cert_chain, key_der)
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Invalid certificate or key: {e}"),
                )
            })?;

        #[cfg(feature = "http3")]
        {
            tls_config.alpn_protocols = alpn_protocols(true);
        }
        #[cfg(not(feature = "http3"))]
        {
            tls_config.alpn_protocols = alpn_protocols(false);
        }

        let tls_config = Arc::new(tls_config);
        let tls_acceptor = TlsAcceptor::from(tls_config.clone());
        let https_port = parse_port(tls_addr, 443);

        let redirect_info = if let Some(cleartext_addr) = cleartext_addr {
            let redirect_addr: std::net::SocketAddr = cleartext_addr
                .parse()
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
            Some((redirect_addr, https_port))
        } else {
            None
        };

        // Start HTTP/3 QUIC Server (if the feature is enabled).
        #[cfg(feature = "http3")]
        {
            let quic_tls = s2n_quic::provider::tls::rustls::Server::from(tls_config);
            let quic_limits = s2n_quic::provider::limits::Limits::new()
                .with_data_window(1_048_576)?
                .with_bidirectional_local_data_window(1_048_576)?
                .with_bidirectional_remote_data_window(1_048_576)?
                .with_initial_round_trip_time(Duration::from_millis(100))?
                .with_max_open_remote_bidirectional_streams(4096)?
                .with_ack_elicitation_interval(4)?
                .with_active_connection_migration(false)?
                .with_max_active_connection_ids(2)?
                .with_max_handshake_duration(Duration::from_secs(5))?;
            let quic_server = s2n_quic::Server::builder()
                .with_tls(quic_tls)?
                .with_limits(quic_limits)?
                .with_io(tls_addr)?
                .start()?;

            let server_h3 = self.clone();
            drop(tokio::spawn(async move {
                let _ = server_h3.serve_h3(quic_server).await;
            }));
        }

        // Start the HTTPS listener (blocks this task).
        let addr: std::net::SocketAddr = tls_addr
            .parse()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        let tls_acceptor = Arc::new(tls_acceptor);
        run_worker_pool(self, addr, redirect_info, move |server, listener| {
            let tls_acceptor = tls_acceptor.clone();
            async move { server.serve_https(listener, (*tls_acceptor).clone()).await }
        })
        .await?;

        Ok(())
    }
}

/// Enforces FIPS compliance on the cryptographic module.
/// If the `fips` feature is enabled and `aws-lc-rs` is not running in FIPS mode,
/// returns an error to prevent server startup.
#[allow(dead_code, clippy::unnecessary_wraps, clippy::missing_const_for_fn)]
pub(crate) fn enforce_fips_compliance() -> Result<(), std::io::Error> {
    // `aws_lc_rs` (the crate) is only linked at all when `tls` is enabled (see `dep:aws-lc-rs`
    // in Cargo.toml) — `tor`/`i2p` no longer pull `tls` in unconditionally, so a
    // `tor`/`i2p` + `fips` build with `tls` left off has no top-level crypto provider of ours
    // to check here. (`tachyon-i2p/fips`, forwarded by this crate's own `fips` feature, still
    // governs `libi2pd`'s *own* separately-linked crypto backend independently of this check.)
    #[cfg(all(feature = "fips", feature = "tls"))]
    {
        if let Err(e) = aws_lc_rs::try_fips_mode() {
            return Err(std::io::Error::other(format!(
                "FIPS compliance check failed: {e}. Cryptographic backend is not in FIPS mode!"
            )));
        }
    }
    Ok(())
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Builds the ALPN protocol list for a TLS `ServerConfig`, in preference order,
/// matching whichever of `http3`/`http2`/`http1` are actually compiled in — so
/// TLS never advertises a protocol the connection-handling code (gated on the
/// same features, see `server/http.rs`) has no branch to serve it with.
#[cfg(feature = "tls")]
pub(crate) fn alpn_protocols(include_h3: bool) -> Vec<Vec<u8>> {
    let mut protocols = Vec::with_capacity(3);
    if include_h3 {
        protocols.push(b"h3".to_vec());
    }
    #[cfg(feature = "http2")]
    protocols.push(b"h2".to_vec());
    #[cfg(feature = "http1")]
    protocols.push(b"http/1.1".to_vec());
    protocols
}

/// Parses the port number from a bind address string (e.g., `"0.0.0.0:443"`).
/// Falls back to `default_port` if parsing fails.
#[cfg(any(feature = "cert-gen", feature = "lets-encrypt"))]
fn parse_port(addr: &str, default_port: u16) -> u16 {
    addr.split(':')
        .next_back()
        .and_then(|p| p.parse::<u16>().ok())
        .unwrap_or(default_port)
}

pub(crate) fn is_resource_exhaustion(e: &std::io::Error) -> bool {
    matches!(e.raw_os_error(), Some(23 | 24 | 10024))
}

/// Runs a plain HTTP listener that serves two functions:
///
/// 1. **ACME HTTP-01 challenges**: Any request to `/.well-known/acme-challenge/<token>`
///    is answered with the key authorization string from the global challenge store.
///    This allows Let's Encrypt to validate domain ownership.
///
/// 2. **HTTPS redirect**: All other requests receive a `308 Permanent Redirect` to the
///    equivalent HTTPS URL. `308` (Permanent Redirect) is preferred over `301` (Moved Permanently)
///    because `308` preserves the request method, which is important for `POST` requests.
#[cfg(feature = "tls")]
pub async fn serve_http_redirect_and_challenges(listener: TcpListener, https_port: u16) {
    let builder =
        hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new());

    loop {
        let (stream, _peer) = match listener.accept().await {
            Ok(c) => c,
            Err(e) => {
                tracing::error!("[http-redirect] Accept error: {e}");
                if is_resource_exhaustion(&e) {
                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                }
                continue;
            }
        };
        let _ = stream.set_nodelay(true);
        let io = hyper_util::rt::TokioIo::new(stream);
        let builder = builder.clone();

        drop(tokio::spawn(async move {
            let _ = builder
                .serve_connection(
                    io,
                    service_fn(move |req: Request<hyper::body::Incoming>| {
                        async move {
                            // Serve ACME HTTP-01 challenge response.
                            #[cfg(feature = "lets-encrypt")]
                            if let Some(token) = req
                                .uri()
                                .path()
                                .strip_prefix("/.well-known/acme-challenge/")
                                && let Some(key_auth) = crate::tls::acme::get_challenge(token)
                            {
                                let resp = Response::builder()
                                    .status(200)
                                    .header("content-type", "text/plain")
                                    .body(Body::full(bytes::Bytes::from(key_auth)))
                                    .unwrap_or_else(|_| Response::new(Body::empty()));
                                return Ok::<_, std::convert::Infallible>(resp);
                            }

                            // 308 Permanent Redirect to HTTPS (preserves method).
                            let host = req
                                .headers()
                                .get("host")
                                .and_then(|h| h.to_str().ok())
                                .unwrap_or("localhost");
                            let host_no_port = host.split(':').next().unwrap_or("localhost");
                            let port_suffix = if https_port == 443 {
                                String::new()
                            } else {
                                format!(":{https_port}")
                            };
                            let path_and_query = req
                                .uri()
                                .path_and_query()
                                .map_or("/", hyper::http::uri::PathAndQuery::as_str);
                            let location =
                                format!("https://{host_no_port}{port_suffix}{path_and_query}");

                            let resp = Response::builder()
                                .status(308) // 308 Permanent Redirect preserves the HTTP method.
                                .header("location", &location)
                                .body(Body::empty())
                                .unwrap_or_else(|_| Response::new(Body::empty()));
                            Ok::<_, std::convert::Infallible>(resp)
                        }
                    }),
                )
                .await;
        }));
    }
}

/// Start serving requests from the given `TcpListener` using the provided `Router`.
///
/// This resolves the listener's local address, automatically compiles the router,
/// and runs the high-performance worker pool.
///
/// # Errors
///
/// Returns an error if compiling the router fails, or if binding/running the server workers fails.
pub async fn serve(
    listener: tokio::net::TcpListener,
    router: crate::routing::Router<()>,
) -> Result<(), std::io::Error> {
    let addr = listener.local_addr()?;
    // drop the listener so the port is free to bind SO_REUSEPORT sockets in the worker pool
    drop(listener);

    let server = Server::new(router);
    server.start_http_addr(addr).await
}

/// Configuration for custom rustls server.
#[cfg(feature = "tls")]
#[derive(Clone)]
pub struct RustlsConfig {
    pub(crate) server_config: Arc<rustls::ServerConfig>,
}

#[cfg(feature = "tls")]
impl std::fmt::Debug for RustlsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RustlsConfig").finish_non_exhaustive()
    }
}

#[cfg(feature = "tls")]
impl RustlsConfig {
    /// Create a new `RustlsConfig` from PEM-formatted certificate chain and private key bytes.
    ///
    /// # Errors
    /// Returns an error if the certificates or private key cannot be parsed, or if the config is invalid.
    #[allow(clippy::unused_async)]
    pub async fn from_pem(cert: Vec<u8>, key: Vec<u8>) -> Result<Self, std::io::Error> {
        use rustls::pki_types::{CertificateDer, PrivateKeyDer};
        use rustls_pemfile::{certs, private_key};

        let mut cert_reader = std::io::BufReader::new(cert.as_slice());
        let cert_chain: Vec<CertificateDer<'static>> = certs(&mut cert_reader)
            .filter_map(std::result::Result::ok)
            .collect();

        let mut key_reader = std::io::BufReader::new(key.as_slice());
        let key_der: PrivateKeyDer<'static> = private_key(&mut key_reader)
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Failed to read private key: {e}"),
                )
            })?
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::NotFound, "No private key found in PEM")
            })?;

        let mut server_config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(cert_chain, key_der)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;

        server_config.alpn_protocols = alpn_protocols(false);

        Ok(Self {
            server_config: Arc::new(server_config),
        })
    }
}

/// Create an HTTPS server bound to the given `SocketAddr` using the provided `RustlsConfig`.
#[cfg(feature = "tls")]
#[must_use]
pub const fn bind_rustls(addr: std::net::SocketAddr, config: RustlsConfig) -> HttpsServer {
    HttpsServer {
        addr,
        config,
        serve_http3: false,
    }
}

/// An HTTPS server ready to be run.
#[cfg(feature = "tls")]
pub struct HttpsServer {
    addr: std::net::SocketAddr,
    config: RustlsConfig,
    serve_http3: bool,
}

#[cfg(feature = "tls")]
impl std::fmt::Debug for HttpsServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpsServer")
            .field("addr", &self.addr)
            .field("serve_http3", &self.serve_http3)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "tls")]
impl HttpsServer {
    /// Enable or disable HTTP/3 (QUIC) support on the same port.
    ///
    /// Note: HTTP/3 requires the `http3` feature to be enabled.
    #[must_use]
    pub const fn serve_http3(mut self, enable: bool) -> Self {
        self.serve_http3 = enable;
        self
    }

    /// Run the server with the given router.
    ///
    /// # Errors
    /// Returns an error if compiling the router or running the server fails.
    pub async fn serve(self, router: crate::routing::Router<()>) -> Result<(), std::io::Error> {
        let server = Server::new(router);
        #[cfg_attr(not(feature = "http3"), allow(unused_mut))]
        let mut rustls_config = (*self.config.server_config).clone();

        #[cfg(feature = "http3")]
        if self.serve_http3 {
            // Ensure ALPN lists "h3"
            if !rustls_config.alpn_protocols.iter().any(|p| p == b"h3") {
                rustls_config.alpn_protocols.insert(0, b"h3".to_vec());
            }

            let tls_config_arc = Arc::new(rustls_config.clone());
            let quic_tls = s2n_quic::provider::tls::rustls::Server::from(tls_config_arc);
            let quic_limits = s2n_quic::provider::limits::Limits::new()
                .with_data_window(1_048_576)
                .map_err(std::io::Error::other)?
                .with_bidirectional_local_data_window(1_048_576)
                .map_err(std::io::Error::other)?
                .with_bidirectional_remote_data_window(1_048_576)
                .map_err(std::io::Error::other)?
                .with_initial_round_trip_time(Duration::from_millis(100))
                .map_err(std::io::Error::other)?
                .with_max_open_remote_bidirectional_streams(4096)
                .map_err(std::io::Error::other)?
                .with_ack_elicitation_interval(4)
                .map_err(std::io::Error::other)?
                .with_active_connection_migration(false)
                .map_err(std::io::Error::other)?
                .with_max_active_connection_ids(2)
                .map_err(std::io::Error::other)?
                .with_max_handshake_duration(Duration::from_secs(5))
                .map_err(std::io::Error::other)?;

            let quic_server = s2n_quic::Server::builder()
                .with_tls(quic_tls)
                .map_err(std::io::Error::other)?
                .with_limits(quic_limits)
                .map_err(std::io::Error::other)?
                .with_io(self.addr)
                .map_err(std::io::Error::other)?
                .start()
                .map_err(std::io::Error::other)?;

            let server_h3 = server.clone();
            tokio::spawn(async move {
                let _ = server_h3.serve_h3(quic_server).await;
            });
        }

        server
            .start_https_with_config_addr(self.addr, rustls_config)
            .await
    }
}

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

    /// `Server::clone()` is a hand-written impl (not `#[derive(Clone)]`, since the field
    /// list is feature-gated) — this proves it actually copies every field rather than
    /// silently dropping one when a new field is added.
    #[test]
    #[allow(clippy::redundant_clone)] // the point of this test is exercising `Clone` itself.
    fn clone_preserves_body_size_and_max_connections() {
        let server = Server::new(Router::new())
            .max_body_size(4096)
            .max_connections(7);
        let cloned = server.clone();
        assert_eq!(cloned.max_body_size, 4096);
        assert_eq!(cloned.max_connections, 7);
    }

    #[cfg(feature = "tls")]
    #[test]
    #[allow(clippy::redundant_clone)] // the point of this test is exercising `Clone` itself.
    fn clone_preserves_tls_policy() {
        let server =
            Server::new(Router::new()).tls_policy(crate::tls::TlsPolicy::hardened().tls13_only());
        assert!(server.tls_policy.is_some());
        let cloned = server.clone();
        assert!(cloned.tls_policy.is_some());
    }

    #[test]
    fn max_connections_builder_sets_field() {
        let server = Server::new(Router::new()).max_connections(42);
        assert_eq!(server.max_connections, 42);
        // Default is untouched by an unrelated builder call.
        assert_eq!(server.max_body_size, 2 * 1024 * 1024);
    }

    #[test]
    fn is_resource_exhaustion_matches_known_codes() {
        assert!(is_resource_exhaustion(&std::io::Error::from_raw_os_error(
            24
        )));
        assert!(is_resource_exhaustion(&std::io::Error::from_raw_os_error(
            23
        )));
        assert!(is_resource_exhaustion(&std::io::Error::from_raw_os_error(
            10024
        )));
    }

    #[test]
    fn is_resource_exhaustion_false_for_unrelated_errors() {
        assert!(!is_resource_exhaustion(&std::io::Error::from_raw_os_error(
            2
        )));
        assert!(!is_resource_exhaustion(&std::io::Error::other(
            "not an os error"
        )));
    }

    #[cfg(feature = "tls")]
    #[test]
    fn rustls_config_debug_smoke() {
        let cert = crate::tls::generate_self_signed_cert(vec!["localhost".to_string()])
            .expect("generate self-signed cert");
        let mut server_config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(vec![cert.cert_der], cert.key_der)
            .expect("build server config");
        server_config.alpn_protocols = alpn_protocols(false);
        let config = RustlsConfig {
            server_config: Arc::new(server_config),
        };
        let dbg = format!("{config:?}");
        assert!(dbg.contains("RustlsConfig"));
    }

    #[cfg(feature = "tls")]
    #[tokio::test]
    async fn rustls_config_from_pem_rejects_garbage_input() {
        let err = RustlsConfig::from_pem(b"not a cert".to_vec(), b"not a key".to_vec())
            .await
            .expect_err("garbage PEM must not build a config");
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
    }

    #[cfg(feature = "tls")]
    #[tokio::test]
    async fn rustls_config_from_pem_builds_from_a_valid_self_signed_cert() {
        let cert = crate::tls::generate_self_signed_cert(vec!["localhost".to_string()])
            .expect("generate self-signed cert");
        let config = RustlsConfig::from_pem(cert.cert_pem.into_bytes(), cert.key_pem.into_bytes())
            .await
            .expect("build config from valid PEM");
        assert!(!config.server_config.alpn_protocols.is_empty());
    }

    #[cfg(feature = "tls")]
    #[test]
    fn bind_rustls_and_https_server_builders() {
        let cert = crate::tls::generate_self_signed_cert(vec!["localhost".to_string()])
            .expect("generate self-signed cert");
        let mut server_config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(vec![cert.cert_der], cert.key_der)
            .expect("build server config");
        server_config.alpn_protocols = alpn_protocols(false);
        let config = RustlsConfig {
            server_config: Arc::new(server_config),
        };
        let addr: std::net::SocketAddr = "127.0.0.1:0".parse().expect("parse addr");

        let https_server = bind_rustls(addr, config);
        assert_eq!(https_server.addr, addr);
        assert!(!https_server.serve_http3);
        let dbg = format!("{https_server:?}");
        assert!(dbg.contains("HttpsServer"));
        assert!(dbg.contains("serve_http3: false"));

        let https_server = https_server.serve_http3(true);
        assert!(https_server.serve_http3);
        let dbg = format!("{https_server:?}");
        assert!(dbg.contains("serve_http3: true"));
    }
}