http-net 0.2.0

Sans-IO HTTP/1.1 server and client: strict RFC 9112 parsing, smuggling defences, bounded buffers, keep-alive, chunked bodies, upgrades, a blocking std adapter, no dependencies.
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
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
//! A small blocking adapter over `std::net`: the Tier-1 path.
//!
//! [`Server`] serves a handler on a socket with one thread per connection
//! (bounded by [`ServerConfig::with_max_connections`]); [`Connection`] is the
//! per-connection loop for callers who run their own accept loop or need the
//! socket back after an upgrade; [`get`] fetches a URL. Everything here is a
//! thin shell around [`ServerConn`] and [`ClientConn`]: all parsing, framing,
//! and limit enforcement happens in the sans-IO core.
//!
//! Only plain `http://` is spoken; there is no TLS in this crate.

use std::{
    fmt, io,
    io::{Read, Write},
    net::{
        IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs,
    },
    string::{String, ToString},
    sync::{
        Arc, Condvar, Mutex,
        atomic::{AtomicBool, Ordering},
    },
    thread,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
    vec::Vec,
};

use crate::{
    ClientConn, ClientEvent, HttpError, Limits, Method, Request, RequestHead, Response, ServerConn,
    ServerEvent,
};

/// Bytes a closing connection reads and discards so the peer's unread data
/// does not turn the close into a reset that destroys the last response.
const DRAIN_LIMIT: usize = 256 * 1024;
/// How long one read of the lingering close may wait.
const DRAIN_READ_TIMEOUT: Duration = Duration::from_millis(250);
/// How long the whole lingering close may take, however the peer behaves:
/// a peer that keeps sending must not keep the connection (and its slot).
const DRAIN_TOTAL: Duration = Duration::from_secs(1);
/// Responses larger than this do not keep their output buffer afterwards.
const OUT_RETAIN: usize = 64 * 1024;

/// What can go wrong in the blocking adapter.
///
/// # Examples
///
/// ```
/// let err = http_net::blocking::get("https://example.com/").unwrap_err();
/// assert!(matches!(err, http_net::blocking::Error::InvalidUrl(_)));
/// ```
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// The socket failed (connect, read, write, or timeout).
    Io(io::Error),
    /// The peer sent a message this crate refuses, or a call was out of
    /// order.
    Http(HttpError),
    /// The URL is not `http://host[:port][/path][?query]`; the text says
    /// which part is wrong.
    InvalidUrl(&'static str),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "I/O error: {e}"),
            Self::Http(e) => write!(f, "HTTP error: {e}"),
            Self::InvalidUrl(why) => write!(f, "invalid URL: {why}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::Http(e) => Some(e),
            Self::InvalidUrl(_) => None,
        }
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<HttpError> for Error {
    fn from(e: HttpError) -> Self {
        Self::Http(e)
    }
}

/// Settings for [`Server`].
///
/// | Setting | Default |
/// |---|---|
/// | limits | [`Limits::new`] |
/// | concurrent connections | 64 (the 65th is answered `503` and closed) |
/// | read timeout (also the idle keep-alive timeout) | 10 s |
/// | request timeout (first byte of a request to the end of its body) | 30 s |
/// | write timeout | 10 s |
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use http_net::{blocking::ServerConfig, Limits};
///
/// let config = ServerConfig::new()
///     .with_limits(Limits::new().with_max_body(16 * 1024))
///     .with_max_connections(8)
///     .with_read_timeout(Some(Duration::from_secs(5)));
/// assert_eq!(config.max_connections(), 8);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServerConfig {
    limits: Limits,
    max_connections: usize,
    read_timeout: Option<Duration>,
    request_timeout: Option<Duration>,
    write_timeout: Option<Duration>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl ServerConfig {
    /// The defaults (see the table on [`ServerConfig`]).
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(http_net::blocking::ServerConfig::new().max_connections(), 64);
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            limits: Limits::new(),
            max_connections: 64,
            read_timeout: Some(Duration::from_secs(10)),
            request_timeout: Some(Duration::from_secs(30)),
            write_timeout: Some(Duration::from_secs(10)),
        }
    }

    /// Sets the message limits for every connection.
    ///
    /// # Examples
    ///
    /// ```
    /// let c = http_net::blocking::ServerConfig::new()
    ///     .with_limits(http_net::Limits::new().with_max_headers(10));
    /// assert_eq!(c.limits().max_headers(), 10);
    /// ```
    #[must_use]
    pub const fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Sets how many connections are served at once (at least 1).
    ///
    /// # Examples
    ///
    /// ```
    /// let c = http_net::blocking::ServerConfig::new().with_max_connections(0);
    /// assert_eq!(c.max_connections(), 1);
    /// ```
    #[must_use]
    pub const fn with_max_connections(mut self, n: usize) -> Self {
        self.max_connections = if n == 0 { 1 } else { n };
        self
    }

    /// Sets the socket read timeout: how long a request may take to arrive,
    /// and how long an idle keep-alive connection is held. `None` waits
    /// forever.
    ///
    /// # Examples
    ///
    /// ```
    /// let c = http_net::blocking::ServerConfig::new().with_read_timeout(None);
    /// assert_eq!(c.read_timeout(), None);
    /// ```
    #[must_use]
    pub const fn with_read_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.read_timeout = timeout;
        self
    }

    /// Sets the request timeout: the most time one request may take to
    /// arrive, from its first byte to the end of its body. The read timeout
    /// alone cannot stop a client that sends one byte just inside it
    /// ("slowloris"); this deadline can. A request still incomplete when it
    /// passes is answered `408 Request Timeout` and the connection closed.
    /// Time spent idle between keep-alive requests does not count (the read
    /// timeout governs that). `None` disables the deadline.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// let c = http_net::blocking::ServerConfig::new().with_request_timeout(Some(Duration::from_secs(10)));
    /// assert_eq!(c.request_timeout(), Some(Duration::from_secs(10)));
    /// ```
    #[must_use]
    pub const fn with_request_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.request_timeout = timeout;
        self
    }

    /// Sets the socket write timeout. `None` waits forever.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// let c = http_net::blocking::ServerConfig::new().with_write_timeout(Some(Duration::from_secs(1)));
    /// assert_eq!(c.write_timeout(), Some(Duration::from_secs(1)));
    /// ```
    #[must_use]
    pub const fn with_write_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.write_timeout = timeout;
        self
    }

    /// The message limits.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(http_net::blocking::ServerConfig::new().limits(), http_net::Limits::new());
    /// ```
    #[must_use]
    pub const fn limits(&self) -> Limits {
        self.limits
    }

    /// The concurrent connection cap.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(http_net::blocking::ServerConfig::new().max_connections(), 64);
    /// ```
    #[must_use]
    pub const fn max_connections(&self) -> usize {
        self.max_connections
    }

    /// The read timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// assert_eq!(http_net::blocking::ServerConfig::new().read_timeout(), Some(Duration::from_secs(10)));
    /// ```
    #[must_use]
    pub const fn read_timeout(&self) -> Option<Duration> {
        self.read_timeout
    }

    /// The request timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// assert_eq!(http_net::blocking::ServerConfig::new().request_timeout(), Some(Duration::from_secs(30)));
    /// ```
    #[must_use]
    pub const fn request_timeout(&self) -> Option<Duration> {
        self.request_timeout
    }

    /// The write timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// assert_eq!(http_net::blocking::ServerConfig::new().write_timeout(), Some(Duration::from_secs(10)));
    /// ```
    #[must_use]
    pub const fn write_timeout(&self) -> Option<Duration> {
        self.write_timeout
    }
}

/// A connection handed over by a `101 Switching Protocols` (or a 2xx to
/// `CONNECT`): the socket, the bytes of the new protocol that already
/// arrived, and the target of the request that asked for the switch.
///
/// # Examples
///
/// ```no_run
/// use http_net::{blocking::Server, Response};
///
/// let server = Server::bind("127.0.0.1:0")?.on_upgrade(|up| {
///     // Hand `up.stream` and `up.leftover` to a protocol engine.
///     let _ = (up.stream, up.leftover, up.target);
/// });
/// server.serve(|req, _body| {
///     if req.is_upgrade() {
///         Response::switching_protocols("x")
///     } else {
///         Response::new(404)
///     }
/// })?;
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug)]
pub struct Upgraded {
    /// The socket, now speaking the new protocol.
    pub stream: TcpStream,
    /// Bytes of the new protocol received together with the request.
    pub leftover: Vec<u8>,
    /// The target of the request that asked for the switch.
    pub target: String,
}

type UpgradeHook = Arc<dyn Fn(Upgraded) + Send + Sync>;

/// A blocking HTTP/1.1 server: one thread per connection, bounded.
///
/// # Examples
///
/// ```
/// use http_net::{blocking::{self, Server}, Response};
///
/// let server = Server::bind("127.0.0.1:0")?;
/// let addr = server.local_addr();
/// let stop = server.shutdown_handle();
/// let thread = std::thread::spawn(move || {
///     server.serve(|req, _body| Response::text(200, &format!("you asked for {}", req.path())))
/// });
///
/// let resp = blocking::get(&format!("http://{addr}/hello"))?;
/// assert_eq!(resp.status(), 200);
/// assert_eq!(resp.text(), Some("you asked for /hello"));
///
/// stop.shutdown();
/// thread.join().unwrap()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Server {
    listener: TcpListener,
    local: SocketAddr,
    config: ServerConfig,
    stop: Arc<AtomicBool>,
    upgrade: Option<UpgradeHook>,
}

impl fmt::Debug for Server {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Server")
            .field("local_addr", &self.local)
            .field("config", &self.config)
            .finish()
    }
}

/// Stops a running [`Server::serve`] from another thread.
///
/// # Examples
///
/// ```
/// let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
/// let stop = server.shutdown_handle();
/// let t = std::thread::spawn(move || server.serve(|_, _| http_net::Response::new(204)));
/// stop.shutdown();
/// t.join().unwrap()?;
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct ShutdownHandle {
    stop: Arc<AtomicBool>,
    wake: SocketAddr,
}

impl ShutdownHandle {
    /// Asks the server to stop: it accepts no new connections, lets each
    /// open connection finish its current exchange, waits for them, and
    /// returns from `serve`.
    ///
    /// # Examples
    ///
    /// See [`ShutdownHandle`].
    pub fn shutdown(&self) {
        self.stop.store(true, Ordering::SeqCst);
        // `accept` blocks; a throwaway connection wakes it so it sees the
        // flag. If the connect fails the listener is already gone, which is
        // the outcome being asked for, so the error carries no information.
        if let Ok(stream) = TcpStream::connect_timeout(&self.wake, Duration::from_secs(1)) {
            drop(stream);
        }
    }
}

/// Counts live connection threads so shutdown can wait for them.
#[derive(Default)]
struct Active {
    count: Mutex<usize>,
    idle: Condvar,
}

impl Active {
    fn try_enter(&self, max: usize) -> bool {
        let mut n = self
            .count
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if *n >= max {
            return false;
        }
        *n += 1;
        true
    }

    fn leave(&self) {
        let mut n = self
            .count
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *n = n.saturating_sub(1);
        if *n == 0 {
            self.idle.notify_all();
        }
    }

    fn wait_idle(&self) {
        let mut n = self
            .count
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while *n > 0 {
            n = self
                .idle
                .wait(n)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
    }
}

/// Leaves the active set even if the handler panics.
struct ActiveGuard(Arc<Active>);

impl Drop for ActiveGuard {
    fn drop(&mut self) {
        self.0.leave();
    }
}

impl Server {
    /// Binds a listening socket. Use `127.0.0.1:0` for an ephemeral
    /// localhost port and read it back with [`local_addr`](Self::local_addr).
    ///
    /// # Errors
    ///
    /// The bind error from the operating system.
    ///
    /// # Examples
    ///
    /// ```
    /// let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
    /// assert!(server.local_addr().ip().is_loopback());
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn bind(addr: impl ToSocketAddrs) -> io::Result<Self> {
        let listener = TcpListener::bind(addr)?;
        let local = listener.local_addr()?;
        Ok(Self {
            listener,
            local,
            config: ServerConfig::new(),
            stop: Arc::new(AtomicBool::new(false)),
            upgrade: None,
        })
    }

    /// Replaces the configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_net::blocking::{Server, ServerConfig};
    /// let s = Server::bind("127.0.0.1:0")?.with_config(ServerConfig::new().with_max_connections(4));
    /// # Ok::<(), std::io::Error>(())
    /// ```
    #[must_use]
    pub fn with_config(mut self, config: ServerConfig) -> Self {
        self.config = config;
        self
    }

    /// Sets what happens to a connection after the handler answers with
    /// `101 Switching Protocols`: `hook` receives the socket on the
    /// connection's thread. Without a hook such connections are closed.
    ///
    /// # Examples
    ///
    /// See [`Upgraded`].
    #[must_use]
    pub fn on_upgrade(mut self, hook: impl Fn(Upgraded) + Send + Sync + 'static) -> Self {
        self.upgrade = Some(Arc::new(hook));
        self
    }

    /// The bound address (with the real port when bound to port 0).
    ///
    /// # Examples
    ///
    /// ```
    /// let server = http_net::blocking::Server::bind("127.0.0.1:0")?;
    /// assert_ne!(server.local_addr().port(), 0);
    /// # Ok::<(), std::io::Error>(())
    /// ```
    #[must_use]
    pub fn local_addr(&self) -> SocketAddr {
        self.local
    }

    /// A handle that stops [`serve`](Self::serve) from another thread.
    ///
    /// # Examples
    ///
    /// See [`ShutdownHandle`].
    #[must_use]
    pub fn shutdown_handle(&self) -> ShutdownHandle {
        let mut wake = self.local;
        if wake.ip().is_unspecified() {
            wake.set_ip(match wake.ip() {
                IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::LOCALHOST),
                IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::LOCALHOST),
            });
        }
        ShutdownHandle {
            stop: Arc::clone(&self.stop),
            wake,
        }
    }

    /// Serves `handler` until [`ShutdownHandle::shutdown`] is called.
    ///
    /// The handler gets each request's head and its complete body (bounded
    /// by [`Limits::max_body`]) and returns the response. Requests that fail
    /// to parse are answered with their [`HttpError::status`] and the
    /// connection is closed; the handler never sees them. Every response
    /// gets a `date` header unless the handler set one.
    ///
    /// # Errors
    ///
    /// Only if accepting connections fails persistently; transient accept
    /// errors are retried.
    ///
    /// # Examples
    ///
    /// See [`Server`].
    pub fn serve<H>(self, handler: H) -> io::Result<()>
    where
        H: Fn(&RequestHead<'_>, &[u8]) -> Response + Send + Sync + 'static,
    {
        let handler = Arc::new(handler);
        let active = Arc::new(Active::default());
        let mut consecutive_errors = 0u32;
        for incoming in self.listener.incoming() {
            if self.stop.load(Ordering::SeqCst) {
                break;
            }
            let stream = match incoming {
                Ok(stream) => {
                    consecutive_errors = 0;
                    stream
                }
                Err(e) => {
                    // Aborted handshakes and descriptor exhaustion are
                    // transient; back off briefly instead of spinning, and
                    // give up only if accept never recovers.
                    consecutive_errors += 1;
                    if consecutive_errors > 1000 {
                        return Err(e);
                    }
                    thread::sleep(Duration::from_millis(10));
                    continue;
                }
            };
            if !active.try_enter(self.config.max_connections) {
                refuse_busy(stream, &self.config);
                continue;
            }
            let guard = ActiveGuard(Arc::clone(&active));
            let handler = Arc::clone(&handler);
            let upgrade = self.upgrade.clone();
            let stop = Arc::clone(&self.stop);
            let config = self.config;
            let spawned = thread::Builder::new()
                .name("http-net-conn".into())
                .spawn(move || {
                    let _guard = guard;
                    serve_stream(stream, &config, &*handler, upgrade.as_deref(), &stop);
                });
            // A failed spawn drops the closure, its guard, and the stream:
            // the connection is closed and the slot released.
            drop(spawned);
        }
        active.wait_idle();
        Ok(())
    }
}

fn refuse_busy(mut stream: TcpStream, config: &ServerConfig) {
    const BUSY: &[u8] =
        b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n";
    // Best effort on a connection being turned away: a failure here only
    // means the client already left. This runs on the accept thread, so it
    // must never wait on the peer: the 503 fits in an empty send buffer,
    // and only what has already arrived is drained (without blocking) so
    // that it does not turn the close into a reset.
    if stream.set_write_timeout(config.write_timeout).is_err()
        || stream.write_all(BUSY).is_err()
        || stream.shutdown(Shutdown::Write).is_err()
        || stream.set_nonblocking(true).is_err()
    {
        return;
    }
    let mut scratch = [0u8; 4096];
    let mut drained = 0;
    while drained < DRAIN_LIMIT {
        match stream.read(&mut scratch) {
            Ok(n) if n > 0 => drained += n,
            _ => break,
        }
    }
}

fn serve_stream(
    stream: TcpStream,
    config: &ServerConfig,
    handler: &(dyn Fn(&RequestHead<'_>, &[u8]) -> Response + Send + Sync),
    upgrade: Option<&(dyn Fn(Upgraded) + Send + Sync)>,
    stop: &AtomicBool,
) {
    let configured = stream.set_read_timeout(config.read_timeout).is_ok()
        && stream.set_write_timeout(config.write_timeout).is_ok()
        && stream.set_nodelay(true).is_ok();
    if !configured {
        return;
    }
    let mut conn =
        Connection::new(stream, config.limits).with_request_timeout(config.request_timeout);
    while !stop.load(Ordering::SeqCst) {
        // The handler runs inside the first match; errors (which borrow
        // nothing) are handled in the second, where `conn` is free again.
        let outcome = match conn.next_request() {
            Ok(Some(incoming)) => {
                let head = incoming.head();
                Ok((
                    handler(&head, incoming.body()),
                    head.method() == Method::Head,
                ))
            }
            Ok(None) => break,
            Err(e) => Err(e),
        };
        let (response, is_head) = match outcome {
            Ok(answer) => answer,
            Err(Error::Http(e)) => {
                let status = e.status().unwrap_or(400);
                let message = e.to_string();
                if conn
                    .respond(&Response::text(status, &message).close())
                    .is_err()
                {
                    return;
                }
                break;
            }
            Err(Error::Io(e)) if is_timeout(&e) && conn.request_in_progress() => {
                // A request that did not arrive in time: say so, then
                // close (the rest of it can no longer be framed).
                if conn.send_request_timeout().is_ok() {
                    conn.close();
                }
                return;
            }
            Err(_) => return,
        };
        // `Server` writes full bodies only: the handler has no way to send
        // a streamed one, so it would leave the client waiting. A `HEAD`
        // answer is the exception: it announces a length or chunked
        // framing but carries no body, so it is complete once written.
        let streamed = response.body_bytes().is_none();
        let response = if streamed && !is_head {
            Response::text(
                500,
                "handler error: Server cannot send a streamed response; \
                 use Connection for streaming",
            )
            .close()
        } else {
            response
        };
        match conn.respond(&response) {
            Ok(()) if streamed && is_head => {
                if conn.end_body().is_err() {
                    return;
                }
            }
            Ok(()) => {}
            // Refused before anything was written (a builder error, or a
            // 101 to a request that did not ask): answer 500 instead.
            Err(Error::Http(e)) => {
                let message = format!("handler error: invalid response: {e}");
                if conn
                    .respond(&Response::text(500, &message).close())
                    .is_err()
                {
                    return;
                }
            }
            Err(_) => return,
        }
        if conn.is_upgraded() {
            match (conn.into_upgraded(), upgrade) {
                (Some(up), Some(hook)) => hook(up),
                (Some(up), None) => drain_and_close(up.stream),
                (None, _) => {}
            }
            return;
        }
    }
    conn.close();
}

fn drain_and_close(mut stream: TcpStream) {
    // Lingering close (RFC 9112 section 9.6): stop sending, then read what
    // the peer is still sending so the close does not become a reset that
    // discards the response before the peer reads it.
    // The drain is bounded in bytes and in total time, not only per read:
    // a peer that keeps trickling data must not hold the thread.
    if stream.flush().is_err() || stream.shutdown(Shutdown::Write).is_err() {
        return;
    }
    let deadline = Instant::now() + DRAIN_TOTAL;
    let mut scratch = [0u8; 4096];
    let mut drained = 0;
    while drained < DRAIN_LIMIT {
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero()
            || stream
                .set_read_timeout(Some(left.min(DRAIN_READ_TIMEOUT)))
                .is_err()
        {
            break;
        }
        match stream.read(&mut scratch) {
            Ok(0) | Err(_) => break,
            Ok(n) => drained += n,
        }
    }
}

fn is_timeout(e: &io::Error) -> bool {
    // Unix reports an expired socket timeout as WouldBlock, Windows as
    // TimedOut.
    matches!(
        e.kind(),
        io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
    )
}

/// One request read by [`Connection::next_request`]: its head and its
/// complete body.
///
/// # Examples
///
/// See [`Connection`].
#[derive(Debug)]
pub struct Incoming<'a> {
    head: RequestHead<'a>,
    body: &'a [u8],
}

impl<'a> Incoming<'a> {
    /// The request head.
    ///
    /// # Examples
    ///
    /// See [`Connection`].
    #[must_use]
    pub fn head(&self) -> RequestHead<'a> {
        self.head
    }

    /// The complete request body (empty when there is none).
    ///
    /// # Examples
    ///
    /// See [`Connection`].
    #[must_use]
    pub fn body(&self) -> &'a [u8] {
        self.body
    }
}

/// A blocking server connection: [`ServerConn`] driven over a `TcpStream`.
///
/// Use it for your own accept loop, or to keep the socket after an
/// upgrade with [`into_upgraded`](Self::into_upgraded).
///
/// # Examples
///
/// ```
/// use std::net::{TcpListener, TcpStream};
/// use std::io::{Read, Write};
/// use http_net::{blocking::Connection, Limits, Response};
///
/// let listener = TcpListener::bind("127.0.0.1:0")?;
/// let addr = listener.local_addr()?;
/// let client = std::thread::spawn(move || -> std::io::Result<Vec<u8>> {
///     let mut s = TcpStream::connect(addr)?;
///     s.write_all(b"POST /sum HTTP/1.1\r\nHost: x\r\nContent-Length: 3\r\nConnection: close\r\n\r\n1 2")?;
///     let mut reply = Vec::new();
///     s.read_to_end(&mut reply)?;
///     Ok(reply)
/// });
///
/// let (stream, _) = listener.accept()?;
/// let mut conn = Connection::new(stream, Limits::new());
/// while let Some(req) = conn.next_request()? {
///     let sum: u32 = std::str::from_utf8(req.body())?.split(' ').filter_map(|n| n.parse::<u32>().ok()).sum();
///     let response = Response::text(200, &sum.to_string());
///     conn.respond(&response)?;
/// }
/// conn.close();
/// let reply = client.join().unwrap()?;
/// assert!(reply.ends_with(b"\r\n\r\n3"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct Connection {
    stream: TcpStream,
    conn: ServerConn,
    body: Vec<u8>,
    out: Vec<u8>,
    /// The socket's own read timeout, restored once a request deadline no
    /// longer applies.
    read_timeout: Option<Duration>,
    request_timeout: Option<Duration>,
    /// When the request being read must be complete.
    deadline: Option<Instant>,
    /// Whether the socket's read timeout is currently shortened to the
    /// deadline.
    shortened: bool,
}

impl Connection {
    /// Wraps an accepted socket. Set its timeouts first if you want them:
    /// the read timeout set on `stream` is the idle timeout, and
    /// [`with_request_timeout`](Self::with_request_timeout) adds a deadline
    /// for each request as a whole.
    ///
    /// # Examples
    ///
    /// See [`Connection`].
    #[must_use]
    pub fn new(stream: TcpStream, limits: Limits) -> Self {
        let read_timeout = stream.read_timeout().ok().flatten();
        Self {
            stream,
            conn: ServerConn::with_limits(limits),
            body: Vec::new(),
            out: Vec::new(),
            read_timeout,
            request_timeout: None,
            deadline: None,
            shortened: false,
        }
    }

    /// Sets a deadline for each request: from the moment its first byte is
    /// seen to the end of its body (see
    /// [`ServerConfig::with_request_timeout`]). When it passes,
    /// [`next_request`](Self::next_request) fails with an [`Error::Io`] of
    /// kind `TimedOut`. `None` (the default for a bare `Connection`) leaves
    /// only the socket's own read timeout.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// # fn demo(stream: std::net::TcpStream) {
    /// let conn = http_net::blocking::Connection::new(stream, http_net::Limits::new())
    ///     .with_request_timeout(Some(Duration::from_secs(10)));
    /// # let _ = conn;
    /// # }
    /// ```
    #[must_use]
    pub fn with_request_timeout(mut self, timeout: Option<Duration>) -> Self {
        self.request_timeout = timeout;
        self
    }

    /// Whether part of a request has arrived and the rest is outstanding.
    fn request_in_progress(&self) -> bool {
        self.conn.request().is_some() || !self.conn.remaining_input().is_empty()
    }

    /// Answers a request that did not arrive in time with `408`, unless a
    /// response is already on its way.
    fn send_request_timeout(&mut self) -> Result<(), Error> {
        if self.conn.response_started() {
            return Err(Error::Http(HttpError::InvalidState(
                "a response was already started",
            )));
        }
        const BODY: &[u8] = b"request timed out";
        self.out.clear();
        self.out.extend_from_slice(
            b"HTTP/1.1 408 Request Timeout\r\ncontent-type: text/plain; charset=utf-8\r\n\
              content-length: ",
        );
        self.out
            .extend_from_slice(BODY.len().to_string().as_bytes());
        self.out
            .extend_from_slice(b"\r\nconnection: close\r\ndate: ");
        self.out.extend_from_slice(&http_date(SystemTime::now()));
        self.out.extend_from_slice(b"\r\n\r\n");
        self.out.extend_from_slice(BODY);
        self.flush_out()
    }

    /// Reads into the parser's buffer, under the request deadline if one
    /// is running.
    fn fill(&mut self) -> Result<(), Error> {
        if let Some(limit) = self.request_timeout {
            if self.deadline.is_none() && self.request_in_progress() {
                self.deadline = Some(Instant::now() + limit);
            }
        }
        match self.deadline {
            Some(deadline) => {
                let left = deadline.saturating_duration_since(Instant::now());
                if left.is_zero() {
                    return Err(Error::Io(io::Error::new(
                        io::ErrorKind::TimedOut,
                        "the request did not arrive within the request timeout",
                    )));
                }
                let wait = self.read_timeout.map_or(left, |t| t.min(left));
                self.stream.set_read_timeout(Some(wait))?;
                self.shortened = true;
            }
            None if self.shortened => {
                self.stream.set_read_timeout(self.read_timeout)?;
                self.shortened = false;
            }
            None => {}
        }
        let spare = self.conn.read_buf();
        if spare.is_empty() {
            return Err(Error::Http(HttpError::InvalidState(
                "input buffer full while the parser needs input",
            )));
        }
        let n = loop {
            match self.stream.read(spare) {
                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                other => break other?,
            }
        };
        if n == 0 {
            self.conn.feed_eof();
        } else {
            self.conn.commit(n);
        }
        Ok(())
    }

    /// Reads the next complete request. `Ok(None)` means the connection is
    /// finished (the client closed between requests, the previous exchange
    /// ended with `connection: close`, or the connection was upgraded).
    ///
    /// A request that carries `Expect: 100-continue` is answered with
    /// `100 Continue` before its body is read.
    ///
    /// # Errors
    ///
    /// [`Error::Http`] for a request this crate refuses (answer it with its
    /// [`HttpError::status`] and close), [`Error::Io`] for socket failures
    /// and timeouts (including the request deadline, as `TimedOut`), and
    /// [`Error::Http`] with [`HttpError::InvalidState`] if the previous
    /// request has not been answered.
    ///
    /// # Examples
    ///
    /// See [`Connection`].
    pub fn next_request(&mut self) -> Result<Option<Incoming<'_>>, Error> {
        self.body.clear();
        self.deadline = None;
        loop {
            match self.conn.poll()? {
                ServerEvent::Request(head) => {
                    // The whole body is read before the caller sees the
                    // request, so the expectation is answered here (RFC 9110
                    // section 10.1.1). A body over the limit was already
                    // refused from its Content-Length.
                    if head.expects_continue() {
                        self.out.clear();
                        self.conn.send_continue(&mut self.out)?;
                        self.flush_out()?;
                    }
                }
                ServerEvent::Body(chunk) => self.body.extend_from_slice(chunk),
                ServerEvent::RequestEnd => break,
                ServerEvent::NeedInput => self.fill()?,
                ServerEvent::AwaitingResponse => {
                    return Err(Error::Http(HttpError::InvalidState(
                        "respond to the previous request first",
                    )));
                }
                _ => return Ok(None),
            }
        }
        match self.conn.request() {
            Some(head) => Ok(Some(Incoming {
                head,
                body: &self.body,
            })),
            None => Ok(None),
        }
    }

    /// Writes `response` to the socket. A streamed response continues with
    /// [`send_body`](Self::send_body) and [`end_body`](Self::end_body).
    ///
    /// # Errors
    ///
    /// [`Error::Http`] when the response is invalid or out of order (see
    /// [`ServerConn::respond`]); [`Error::Io`] when the write fails.
    ///
    /// # Examples
    ///
    /// See [`Connection`].
    pub fn respond(&mut self, response: &Response) -> Result<(), Error> {
        self.out.clear();
        let date = http_date(SystemTime::now());
        self.conn
            .respond_dated(response, Some(&date), &mut self.out)?;
        self.flush_out()
    }

    /// Writes body bytes of a streamed response.
    ///
    /// # Errors
    ///
    /// As [`ServerConn::send_body`], plus [`Error::Io`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn demo(conn: &mut http_net::blocking::Connection) -> Result<(), http_net::blocking::Error> {
    /// conn.respond(&http_net::Response::new(200).chunked())?;
    /// conn.send_body(b"first")?;
    /// conn.end_body()?;
    /// # Ok(()) }
    /// ```
    pub fn send_body(&mut self, data: &[u8]) -> Result<(), Error> {
        self.out.clear();
        self.conn.send_body(data, &mut self.out)?;
        self.flush_out()
    }

    /// Ends a streamed response.
    ///
    /// # Errors
    ///
    /// As [`ServerConn::end_body`], plus [`Error::Io`].
    ///
    /// # Examples
    ///
    /// See [`send_body`](Self::send_body).
    pub fn end_body(&mut self) -> Result<(), Error> {
        self.out.clear();
        self.conn.end_body(&mut self.out)?;
        self.flush_out()
    }

    fn flush_out(&mut self) -> Result<(), Error> {
        self.stream.write_all(&self.out)?;
        if self.out.capacity() > OUT_RETAIN {
            self.out = Vec::new();
        }
        Ok(())
    }

    /// Whether a `101` (or a 2xx to `CONNECT`) was sent.
    ///
    /// # Examples
    ///
    /// See [`into_upgraded`](Self::into_upgraded).
    #[must_use]
    pub fn is_upgraded(&self) -> bool {
        self.conn.is_upgraded()
    }

    /// The socket and the bytes of the new protocol, after an upgrade;
    /// `None` if the connection was not upgraded. The socket's read timeout
    /// is the one it had when the `Connection` was created (a request
    /// deadline may have shortened it while the request was read).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn demo(mut conn: http_net::blocking::Connection) {
    /// if conn.is_upgraded() {
    ///     let up = conn.into_upgraded().unwrap();
    ///     // speak the new protocol on up.stream, starting with up.leftover
    /// #   let _ = up;
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn into_upgraded(self) -> Option<Upgraded> {
        if !self.is_upgraded() {
            return None;
        }
        let target = self
            .conn
            .request()
            .map(|r| r.target().to_string())
            .unwrap_or_default();
        if self.shortened {
            // Best effort: the new protocol must not inherit what was left
            // of the request deadline. Setting a timeout this socket has
            // already accepted does not fail in practice, and the hand-off
            // is more useful than refusing it over one.
            let _ = self.stream.set_read_timeout(self.read_timeout);
        }
        Some(Upgraded {
            leftover: self.conn.remaining_input().to_vec(),
            target,
            stream: self.stream,
        })
    }

    /// Closes the connection gracefully: stops sending, briefly drains what
    /// the client is still sending, and drops the socket.
    ///
    /// # Examples
    ///
    /// See [`Connection`].
    pub fn close(self) {
        drain_and_close(self.stream);
    }
}

/// A response fetched by [`get`] or [`Client::get`], fully read.
///
/// # Examples
///
/// See [`Server`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClientResponse {
    status: u16,
    headers: Vec<(String, Vec<u8>)>,
    body: Vec<u8>,
}

impl ClientResponse {
    /// The status code.
    ///
    /// # Examples
    ///
    /// See [`Server`].
    #[must_use]
    pub fn status(&self) -> u16 {
        self.status
    }

    /// The fields in arrival order.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let resp = http_net::blocking::get("http://127.0.0.1:8080/")?;
    /// for (name, value) in resp.headers() {
    ///     let _ = (name, value);
    /// }
    /// # Ok::<(), http_net::blocking::Error>(())
    /// ```
    pub fn headers(&self) -> impl Iterator<Item = (&str, &[u8])> {
        self.headers.iter().map(|(n, v)| (n.as_str(), v.as_slice()))
    }

    /// The first field named `name` (ASCII case-insensitive).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let resp = http_net::blocking::get("http://127.0.0.1:8080/")?;
    /// let _ = resp.header("content-type");
    /// # Ok::<(), http_net::blocking::Error>(())
    /// ```
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&[u8]> {
        self.headers
            .iter()
            .find(|(n, _)| n.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_slice())
    }

    /// The body.
    ///
    /// # Examples
    ///
    /// See [`Server`].
    #[must_use]
    pub fn body(&self) -> &[u8] {
        &self.body
    }

    /// The body, if it is UTF-8.
    ///
    /// # Examples
    ///
    /// See [`Server`].
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        core::str::from_utf8(&self.body).ok()
    }

    /// Takes the body.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let bytes = http_net::blocking::get("http://127.0.0.1:8080/")?.into_body();
    /// # let _ = bytes;
    /// # Ok::<(), http_net::blocking::Error>(())
    /// ```
    #[must_use]
    pub fn into_body(self) -> Vec<u8> {
        self.body
    }
}

/// Fetches `url` with `GET` using the default [`Client`].
///
/// # Errors
///
/// [`Error::InvalidUrl`] for anything but `http://host[:port][/path]`,
/// [`Error::Io`] for connection failures and timeouts, [`Error::Http`] for
/// a response this crate refuses (including one over the body limit).
///
/// # Examples
///
/// See [`Server`].
pub fn get(url: &str) -> Result<ClientResponse, Error> {
    Client::new().get(url)
}

/// A blocking HTTP/1.1 client: one connection per request.
///
/// | Setting | Default |
/// |---|---|
/// | limits | [`Limits::new`] with a 16 MiB body |
/// | connect, read, and write timeout | 30 s each |
///
/// # Examples
///
/// ```no_run
/// use std::time::Duration;
/// use http_net::{blocking::Client, Limits};
///
/// let client = Client::new()
///     .with_limits(Limits::new().with_max_body(64 << 20))
///     .with_timeout(Duration::from_secs(5));
/// let resp = client.get("http://127.0.0.1:8080/big")?;
/// # let _ = resp;
/// # Ok::<(), http_net::blocking::Error>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Client {
    limits: Limits,
    timeout: Duration,
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

impl Client {
    /// The defaults (see the table on [`Client`]).
    ///
    /// # Examples
    ///
    /// ```
    /// let _ = http_net::blocking::Client::new();
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            limits: Limits::new().with_max_body(16 * 1024 * 1024),
            timeout: Duration::from_secs(30),
        }
    }

    /// Sets the response limits.
    ///
    /// # Examples
    ///
    /// ```
    /// let _ = http_net::blocking::Client::new().with_limits(http_net::Limits::new());
    /// ```
    #[must_use]
    pub const fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Sets the connect, read, and write timeout (zero is raised to 1 ms).
    ///
    /// # Examples
    ///
    /// ```
    /// let _ = http_net::blocking::Client::new().with_timeout(std::time::Duration::from_secs(2));
    /// ```
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = if timeout.is_zero() {
            Duration::from_millis(1)
        } else {
            timeout
        };
        self
    }

    /// Fetches `url` with `GET`.
    ///
    /// # Errors
    ///
    /// As [`get`].
    ///
    /// # Examples
    ///
    /// See [`Client`].
    pub fn get(&self, url: &str) -> Result<ClientResponse, Error> {
        let url = Url::parse(url)?;
        let request = Request::get(url.target)
            .header("host", url.authority)
            .close();
        let mut stream = self.connect(&url)?;
        let mut conn = ClientConn::with_limits(self.limits);
        let mut out = Vec::new();
        conn.send_request(&request, &mut out)?;
        stream.write_all(&out)?;
        read_response(&mut stream, &mut conn)
    }

    fn connect(&self, url: &Url<'_>) -> Result<TcpStream, Error> {
        let mut last = None;
        for addr in (url.host, url.port).to_socket_addrs()? {
            match TcpStream::connect_timeout(&addr, self.timeout) {
                Ok(stream) => {
                    stream.set_read_timeout(Some(self.timeout))?;
                    stream.set_write_timeout(Some(self.timeout))?;
                    stream.set_nodelay(true)?;
                    return Ok(stream);
                }
                Err(e) => last = Some(e),
            }
        }
        Err(Error::Io(last.unwrap_or_else(|| {
            io::Error::new(io::ErrorKind::NotFound, "the host resolved to no address")
        })))
    }
}

fn read_response(stream: &mut TcpStream, conn: &mut ClientConn) -> Result<ClientResponse, Error> {
    let mut response = ClientResponse {
        status: 0,
        headers: Vec::new(),
        body: Vec::new(),
    };
    loop {
        match conn.poll()? {
            ClientEvent::Response(head) => {
                response.status = head.status();
                response.headers = head
                    .headers()
                    .map(|(n, v)| (n.to_string(), v.to_vec()))
                    .collect();
            }
            ClientEvent::Body(chunk) => response.body.extend_from_slice(chunk),
            ClientEvent::ResponseEnd => return Ok(response),
            ClientEvent::NeedInput => {
                let spare = conn.read_buf();
                if spare.is_empty() {
                    return Err(Error::Http(HttpError::InvalidState(
                        "input buffer full while the parser needs input",
                    )));
                }
                let n = loop {
                    match stream.read(spare) {
                        Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                        other => break other?,
                    }
                };
                if n == 0 {
                    conn.feed_eof();
                } else {
                    conn.commit(n);
                }
            }
            _ => {
                return Err(Error::Http(HttpError::InvalidState(
                    "the connection ended without a complete response",
                )));
            }
        }
    }
}

/// The parts of an `http://` URL needed to send a request.
#[derive(Debug, PartialEq, Eq)]
struct Url<'a> {
    /// `host[:port]` as written, for the Host header.
    authority: &'a str,
    /// The host for name resolution (brackets removed from IPv6 literals).
    host: &'a str,
    port: u16,
    /// Path and query; `/` when the URL has no path.
    target: &'a str,
}

impl<'a> Url<'a> {
    fn parse(url: &'a str) -> Result<Self, Error> {
        let scheme_end = url.find("://").ok_or(Error::InvalidUrl("missing scheme"))?;
        if !url[..scheme_end].eq_ignore_ascii_case("http") {
            return Err(Error::InvalidUrl(
                "only http:// is supported (no TLS in this crate)",
            ));
        }
        let rest = &url[scheme_end + 3..];
        // The fragment is never sent.
        let rest = rest.split_once('#').map_or(rest, |(r, _)| r);
        let auth_end = rest.find(['/', '?']).unwrap_or(rest.len());
        let authority = &rest[..auth_end];
        let target = match &rest[auth_end..] {
            "" => "/",
            t if t.starts_with('?') => {
                return Err(Error::InvalidUrl("a query needs a path, for example /?q"));
            }
            t => t,
        };
        if authority.is_empty() {
            return Err(Error::InvalidUrl("missing host"));
        }
        if authority.contains('@') {
            return Err(Error::InvalidUrl(
                "credentials in the URL are not supported",
            ));
        }
        let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
            let (inside, after) = v6.split_once(']').ok_or(Error::InvalidUrl("unclosed ["))?;
            let port = match after {
                "" => None,
                p => Some(
                    p.strip_prefix(':')
                        .ok_or(Error::InvalidUrl("junk after ]"))?,
                ),
            };
            (inside, port)
        } else {
            match authority.rsplit_once(':') {
                Some((h, p)) => (h, Some(p)),
                None => (authority, None),
            }
        };
        let port = match port {
            None => 80,
            Some(p) => p.parse().map_err(|_| Error::InvalidUrl("bad port"))?,
        };
        if host.is_empty() {
            return Err(Error::InvalidUrl("missing host"));
        }
        Ok(Self {
            authority,
            host,
            port,
            target,
        })
    }
}

/// Formats `time` as an IMF-fixdate (RFC 9110 section 5.6.7), for example
/// `Sun, 06 Nov 1994 08:49:37 GMT`.
fn http_date(time: SystemTime) -> [u8; 29] {
    let secs = time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
    let days = secs / 86_400;
    let rem = secs % 86_400;
    let (year, month, day) = civil_from_days(days);
    const WEEKDAYS: [&[u8; 3]; 7] = [b"Thu", b"Fri", b"Sat", b"Sun", b"Mon", b"Tue", b"Wed"];
    const MONTHS: [&[u8; 3]; 12] = [
        b"Jan", b"Feb", b"Mar", b"Apr", b"May", b"Jun", b"Jul", b"Aug", b"Sep", b"Oct", b"Nov",
        b"Dec",
    ];
    let mut out = *b"Thu, 01 Jan 1970 00:00:00 GMT";
    out[..3].copy_from_slice(WEEKDAYS[(days % 7) as usize]);
    two_digits(&mut out[5..7], day);
    out[8..11].copy_from_slice(MONTHS[(month - 1) as usize]);
    let y = year.min(9999);
    two_digits(&mut out[12..14], y / 100);
    two_digits(&mut out[14..16], y % 100);
    two_digits(&mut out[17..19], rem / 3600);
    two_digits(&mut out[20..22], rem % 3600 / 60);
    two_digits(&mut out[23..25], rem % 60);
    out
}

fn two_digits(dst: &mut [u8], v: u64) {
    if let [tens, ones] = dst {
        *tens = b'0' + (v / 10 % 10) as u8;
        *ones = b'0' + (v % 10) as u8;
    }
}

/// Days since 1970-01-01 to (year, month 1..=12, day 1..=31), after Howard
/// Hinnant's `civil_from_days`, restricted to dates on or after the epoch.
fn civil_from_days(days: u64) -> (u64, u64, u64) {
    let z = days + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + u64::from(month <= 2);
    (year, month, day)
}

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

    #[test]
    fn test_http_date_known_values() {
        let at = |s: u64| UNIX_EPOCH + Duration::from_secs(s);
        assert_eq!(&http_date(at(0)), b"Thu, 01 Jan 1970 00:00:00 GMT");
        assert_eq!(
            &http_date(at(784_111_777)),
            b"Sun, 06 Nov 1994 08:49:37 GMT"
        );
        assert_eq!(
            &http_date(at(951_782_400)),
            b"Tue, 29 Feb 2000 00:00:00 GMT"
        );
        assert_eq!(
            &http_date(at(1_791_072_000)),
            b"Sun, 04 Oct 2026 00:00:00 GMT"
        );
    }

    #[test]
    fn test_url_parsing() {
        let u = Url::parse("http://127.0.0.1:8080/a/b?c=d#frag").unwrap();
        assert_eq!(
            u,
            Url {
                authority: "127.0.0.1:8080",
                host: "127.0.0.1",
                port: 8080,
                target: "/a/b?c=d"
            }
        );
        let u = Url::parse("HTTP://[::1]/").unwrap();
        assert_eq!((u.host, u.port, u.authority), ("::1", 80, "[::1]"));
        assert_eq!(Url::parse("http://example.com").unwrap().target, "/");
        for bad in [
            "example.com",
            "https://x/",
            "http:///x",
            "http://u:p@x/",
            "http://x:99999/",
            "http://[::1/",
            "http://[::1]x/",
            "http://x?q",
            "http://:80/",
        ] {
            assert!(
                matches!(Url::parse(bad), Err(Error::InvalidUrl(_))),
                "{bad}"
            );
        }
    }

    #[test]
    fn test_error_display_and_source() {
        use std::error::Error as _;
        let e = Error::from(HttpError::BareCr);
        assert!(e.to_string().starts_with("HTTP error"));
        assert!(e.source().is_some());
        let e = Error::from(io::Error::other("x"));
        assert!(e.source().is_some());
        assert!(Error::InvalidUrl("y").source().is_none());
    }
}