tcp/
states.rs

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
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
use std::collections::{HashMap, LinkedList};
use std::io::{Read, Write};
use std::net::SocketAddrV4;

use crate::buffer::RecvQueue;
use crate::connection::Connection;
use crate::seq::Seq;
use crate::util::remove_from_list;
use crate::util::time::Duration;
use crate::{
    AcceptError, AcceptedTcpState, CloseError, ConnectError, Dependencies, ListenError, Payload,
    PollState, PopPacketError, PushPacketError, RecvError, RstCloseError, SendError, Shutdown,
    ShutdownError, TcpConfig, TcpError, TcpFlags, TcpHeader, TcpState, TcpStateEnum, TcpStateTrait,
    TimerRegisteredBy,
};

// state structs

/// The initial state of the TCP socket. While it's not a part of the official TCP state diagram, we
/// don't want to overload the "closed" state to mean both a closed socket and a never used socket,
/// since we don't allow TCP socket re-use.
#[derive(Debug)]
pub struct InitState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) config: TcpConfig,
}

#[derive(Debug)]
pub struct ListenState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) config: TcpConfig,
    pub(crate) max_backlog: u32,
    pub(crate) send_buffer: LinkedList<TcpHeader>,
    /// Child TCP states.
    ///
    /// Child states should only be mutated through the [`with_child`](Self::with_child) method to
    /// ensure that this parent stays in sync with the child.
    pub(crate) children: slotmap::DenseSlotMap<ChildTcpKey, ChildEntry<X>>,
    /// A map from 4 tuple (source address, destination address) to child. Packets received from the
    /// source address will be forwarded to the child.
    pub(crate) conn_map: HashMap<RemoteLocalPair, ChildTcpKey>,
    /// A queue of child TCP states in the "established" state, ready to be accept()ed.
    pub(crate) accept_queue: LinkedList<ChildTcpKey>,
    /// A list of child TCP states that want to send a packet.
    pub(crate) to_send: LinkedList<ChildTcpKey>,
}

#[derive(Debug)]
pub struct SynSentState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct SynReceivedState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct EstablishedState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct FinWaitOneState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct FinWaitTwoState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct ClosingState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct TimeWaitState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct CloseWaitState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

#[derive(Debug)]
pub struct LastAckState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) connection: Connection<X::Instant>,
}

/// A state for sockets that need to send RST packets before closing. While it's not a part of the
/// official TCP state diagram, we need to be able to buffer RST packets to send. We can't buffer
/// RST packets in the "closed" state since the "closed" state is not allowed to send packets, so we
/// use this as an intermediate state before we move to the "closed" state. We may need to buffer
/// several RST packets; for example states in the "listening" state might need to send an RST
/// packet for each child.
#[derive(Debug)]
pub struct RstState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) send_buffer: LinkedList<TcpHeader>,
    /// Was the socket previously connected? Should be `true` for any states that have previously
    /// been in the "syn-sent" or "syn-received" states. The connection does not need to have been
    /// successful (for example it may have timed out in the "syn-sent" state or may have been
    /// reset).
    pub(crate) was_connected: bool,
}

#[derive(Debug)]
pub struct ClosedState<X: Dependencies> {
    pub(crate) common: Common<X>,
    pub(crate) recv_buffer: RecvQueue,
    /// Was the socket previously connected? Should be `true` for any states that have previously
    /// been in the "syn-sent" or "syn-received" states. The connection does not need to have been
    /// successful (for example it may have timed out in the "syn-sent" state or may have been
    /// reset).
    pub(crate) was_connected: bool,
}

// other helper types

/// Indicates that no child exists for the given [key](ChildTcpKey).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct ChildNotFound;

#[derive(Debug)]
pub(crate) struct Common<X: Dependencies> {
    pub(crate) deps: X,
    /// If the current state is a child of a parent state, this should be the key that the parent
    /// can use to lookup ths child state.
    pub(crate) child_key: Option<ChildTcpKey>,
    pub(crate) error: Option<TcpError>,
}

impl<X: Dependencies> Common<X> {
    /// Register a timer for this state.
    ///
    /// This method will make sure that the callback gets run on the correct state, even if called
    /// by a child state.
    pub fn register_timer(
        &self,
        time: X::Instant,
        f: impl FnOnce(TcpStateEnum<X>) -> TcpStateEnum<X> + Send + Sync + 'static,
    ) {
        // the handle that identifies this state if the state is a child of some parent state
        let child_key = self.child_key;

        // takes an owned `TcpStateEnum` and returns a `TcpStateEnum`
        let timer_cb_inner = move |mut parent_state, state_type| {
            match state_type {
                // we're the parent and the timer was registered by us
                TimerRegisteredBy::Parent => f(parent_state),
                // we're the parent and the timer was registered by a child
                TimerRegisteredBy::Child => {
                    // if not in the listening state anymore, then the child must not exist
                    let TcpStateEnum::Listen(parent_listen_state) = &mut parent_state else {
                        // do nothing
                        return parent_state;
                    };

                    // we need to lookup the child in `state` and run f() on the child's state
                    // instead

                    let child_key = child_key.expect(
                        "The timer was supposedly registered by a child state, but there was no \
                        key to identify the child",
                    );

                    let rv = parent_listen_state.with_child(child_key, |state| (f(state), ()));

                    // in practice we want to ignore the error, but by doing a match here we make
                    // sure that if the return type of `with_child` changes in the future, this code
                    // will break and we can update it
                    #[allow(clippy::single_match)]
                    match rv {
                        Ok(()) => {}
                        // we ignore this since the child may have been closed
                        Err(ChildNotFound) => {}
                    }

                    parent_state
                }
            }
        };

        // mutates a reference to a `TcpState` (this is a separate closure since it saves us two
        // levels of indentation in the inner closure above)
        let timer_cb = move |parent_state: &mut TcpState<X>, state_type| {
            parent_state.with_state(|state| (timer_cb_inner(state, state_type), ()))
        };

        self.deps.register_timer(time, timer_cb);
    }

    pub fn current_time(&self) -> X::Instant {
        self.deps.current_time()
    }

    /// Returns true if the error was set, or false if the error was previously set and was not
    /// modified.
    pub fn set_error_if_unset(&mut self, new_error: TcpError) -> bool {
        if self.error.is_none() {
            self.error = Some(new_error);
            return true;
        }

        false
    }
}

/// A pair of remote and local addresses, typically used to represent a connection (the 4-tuple).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct RemoteLocalPair {
    /// The remote address (where a received packet was addressed from, or the address we're sending
    /// a packet to).
    remote: SocketAddrV4,
    /// The local address (where a received packet was addressed to, or the address we're sending a
    /// packet from).
    local: SocketAddrV4,
}

impl RemoteLocalPair {
    pub fn new(remote: SocketAddrV4, local: SocketAddrV4) -> Self {
        Self { remote, local }
    }
}

slotmap::new_key_type! { pub(crate) struct ChildTcpKey; }

#[derive(Debug)]
pub(crate) struct ChildEntry<X: Dependencies> {
    /// The `Option` is required so that we can run [`TcpState`] methods that require `self`, for
    /// example `child.push_packet()`.
    state: Option<TcpStateEnum<X>>,
    conn_addrs: RemoteLocalPair,
}

// state implementations

impl<X: Dependencies> InitState<X> {
    pub fn new(deps: X, config: TcpConfig) -> Self {
        let common = Common {
            deps,
            child_key: None,
            error: None,
        };

        InitState { common, config }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for InitState<X> {
    fn close(self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = ClosedState::new(self.common, None, /* was_connected= */ false);
        (new_state.into(), Ok(()))
    }

    fn rst_close(self) -> (TcpStateEnum<X>, Result<(), RstCloseError>) {
        // no need to send a RST; closing immediately
        let new_state = ClosedState::new(self.common, None, /* was_connected= */ false);
        (new_state.into(), Ok(()))
    }

    fn shutdown(self, _how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        (self.into(), Err(ShutdownError::NotConnected))
    }

    fn listen<T, E>(
        self,
        backlog: u32,
        associate_fn: impl FnOnce() -> Result<T, E>,
    ) -> (TcpStateEnum<X>, Result<T, ListenError<E>>) {
        let rv = match associate_fn() {
            Ok(x) => x,
            Err(e) => return (self.into(), Err(ListenError::FailedAssociation(e))),
        };

        // linux uses a queue limit of one greater than the provided backlog
        let max_backlog = backlog.saturating_add(1);

        let new_state = ListenState::new(self.common, self.config, max_backlog);
        (new_state.into(), Ok(rv))
    }

    fn connect<T, E>(
        self,
        remote_addr: SocketAddrV4,
        associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        let assoc_result = associate_fn();

        let (local_addr, assoc_result) = match assoc_result {
            Ok((local_addr, assoc_result)) => (local_addr, assoc_result),
            Err(e) => return (self.into(), Err(ConnectError::FailedAssociation(e))),
        };

        assert!(!local_addr.ip().is_unspecified());

        let connection = Connection::new(local_addr, remote_addr, Seq::new(0), self.config);

        let new_state = SynSentState::new(self.common, connection);
        (new_state.into(), Ok(assoc_result))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::NotConnected))
    }

    fn recv(self, _writer: impl Write, _len: usize) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        (self.into(), Err(RecvError::NotConnected))
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::empty();

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        false
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        None
    }
}

impl<X: Dependencies> ListenState<X> {
    fn new(common: Common<X>, config: TcpConfig, max_backlog: u32) -> Self {
        ListenState {
            common,
            config,
            max_backlog,
            send_buffer: LinkedList::new(),
            children: slotmap::DenseSlotMap::with_key(),
            conn_map: HashMap::new(),
            accept_queue: LinkedList::new(),
            to_send: LinkedList::new(),
        }
    }

    /// Register a new child TCP state for a new incoming connection.
    fn register_child(&mut self, header: &TcpHeader, payload: Payload) -> ChildTcpKey {
        let conn_addrs = RemoteLocalPair::new(header.src(), header.dst());

        let key = self.children.insert_with_key(|key| {
            let common = Common {
                deps: self.common.deps.fork(),
                child_key: Some(key),
                error: None,
            };

            assert!(header.flags.contains(TcpFlags::SYN));
            assert!(!header.flags.contains(TcpFlags::RST));

            let mut connection =
                Connection::new(header.dst(), header.src(), Seq::new(0), self.config);
            connection.push_packet(header, payload).unwrap();

            let new_tcp = SynReceivedState::new(common, connection);

            ChildEntry {
                state: Some(new_tcp.into()),
                conn_addrs,
            }
        });

        assert!(self.conn_map.insert(conn_addrs, key).is_none());

        // make sure the child is added to all of the correct lists
        self.sync_child(key).unwrap();

        key
    }

    /// Make sure the parent's state is synchronized with the child's state. For example if the
    /// child is in the "established" state, it should be in the parent's accept queue.
    fn sync_child(&mut self, key: ChildTcpKey) -> Result<(), ChildNotFound> {
        let is_closed;

        {
            let entry = self.children.get_mut(key).ok_or(ChildNotFound)?;
            let child = &mut entry.state;
            let conn_addrs = &entry.conn_addrs;

            // add to or remove from the `to_send` list
            if child.as_ref().unwrap().wants_to_send() {
                // if it wants to send a packet but is not in the `to_send` list
                if !self.to_send.contains(&key) {
                    // add to the `to_send` list
                    self.to_send.push_back(key);
                }
            } else {
                // doesn't want to send a packet, remove from the `to_send` list
                remove_from_list(&mut self.to_send, &key);
            }

            // add to or remove from the accept queue
            if matches!(
                child.as_ref().unwrap(),
                TcpStateEnum::Established(_) | TcpStateEnum::CloseWait(_)
            ) {
                // if in the "established" or "close-wait" state, but not in the accept queue
                if !self.accept_queue.contains(&key) {
                    // add to the accept queue
                    self.accept_queue.push_back(key);
                }
            } else {
                // not in the "established" or "close-wait" state; remove from the accept queue
                remove_from_list(&mut self.accept_queue, &key);
            }

            // make sure that it's contained in the src map
            assert!(self.conn_map.contains_key(conn_addrs));
            debug_assert_eq!(self.conn_map.get(conn_addrs).unwrap(), &key);

            is_closed = child.as_ref().unwrap().poll().contains(PollState::CLOSED);
        }

        // if the child is closed, we can drop it
        if is_closed {
            self.remove_child(key).unwrap();
        }

        Ok(())
    }

    /// Remove a child state and all references to it (except timers). Returns `None` if there was
    /// no child with the given key.
    fn remove_child(&mut self, key: ChildTcpKey) -> Option<TcpStateEnum<X>> {
        let entry = self.children.remove(key)?;
        let child = entry.state.unwrap();
        let conn_addrs = entry.conn_addrs;

        // remove the child from any other lists/maps

        remove_from_list(&mut self.accept_queue, &key);
        remove_from_list(&mut self.to_send, &key);
        assert_eq!(self.conn_map.remove(&conn_addrs), Some(key));

        Some(child)
    }

    /// Get the child state.
    fn child(&self, key: ChildTcpKey) -> Option<&TcpStateEnum<X>> {
        self.children.get(key)?.state.as_ref()
    }

    /// Mutate the child's state, and automatically make sure that the parent's state is correctly
    /// synced with the child's state (see [`sync_child`]).
    fn with_child<T>(
        &mut self,
        key: ChildTcpKey,
        f: impl FnOnce(TcpStateEnum<X>) -> (TcpStateEnum<X>, T),
    ) -> Result<T, ChildNotFound> {
        let rv;

        {
            let child = &mut self.children.get_mut(key).ok_or(ChildNotFound)?.state;

            // run the closure
            let mut state = child.take().unwrap();
            (state, rv) = f(state);
            *child = Some(state);
        }

        self.sync_child(key).unwrap();

        Ok(rv)
    }
}

impl<X: Dependencies> TcpStateTrait<X> for ListenState<X> {
    fn close(self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let (new_state, rv) = self.rst_close();
        assert!(rv.is_ok());
        (new_state, Ok(()))
    }

    fn rst_close(mut self) -> (TcpStateEnum<X>, Result<(), RstCloseError>) {
        let child_keys = Vec::from_iter(self.children.keys());

        for key in child_keys {
            self.with_child(key, |child| child.rst_close())
                .unwrap()
                .unwrap();

            // get any packets that it wants to send and add them to our send buffer; removing a
            // packet may cause the child to close which will make `key` invalid, which is why we
            // don't unwrap here
            while let Ok(Ok((header, payload))) = self.with_child(key, |child| child.pop_packet()) {
                assert!(payload.is_empty());
                self.send_buffer.push_back(header);
            }
        }

        // The `rst_close` should have moved the child states to either "closed" or "rst" and
        // possibly queued some RST packets. Then we should have taken those packets from the child
        // state and moved them to our buffer, which would have then moved all child states to
        // "closed". Finally `with_child` would have seen that they closed and removed them from
        // `self.children`.
        assert!(self.children.is_empty());

        // get all rst packets from our send buffer
        let rst_packets: LinkedList<_> = self
            .send_buffer
            .into_iter()
            .filter(|header| header.flags.contains(TcpFlags::RST))
            .collect();

        let new_state = if rst_packets.is_empty() {
            // no RST packets to send, so go directly to the "closed" state
            ClosedState::new(self.common, None, /* was_connected= */ false).into()
        } else {
            RstState::new(self.common, rst_packets, /* was_connected= */ false).into()
        };

        (new_state, Ok(()))
    }

    fn shutdown(self, _how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        // TODO: Linux will reset back to the initial state (allowing future connect(), listen(),
        // etc for the same socket) for SHUT_RD or SHUT_RDWR. But this should probably be handled in
        // a higher layer (for example having the socket replace this tcp state with a new tcp state
        // object).

        (self.into(), Err(ShutdownError::NotConnected))
    }

    fn listen<T, E>(
        mut self,
        backlog: u32,
        associate_fn: impl FnOnce() -> Result<T, E>,
    ) -> (TcpStateEnum<X>, Result<T, ListenError<E>>) {
        // we don't need to associate, but we run this closure anyway; the caller can make this a
        // no-op if it doesn't need to associate
        let rv = match associate_fn() {
            Ok(x) => x,
            Err(e) => return (self.into(), Err(ListenError::FailedAssociation(e))),
        };

        // linux uses a limit of one greater than the provided backlog
        let max_backlog = backlog.saturating_add(1);

        // we're already listening, so must already be associated; just update the backlog
        self.max_backlog = max_backlog;
        (self.into(), Ok(rv))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::IsListening))
    }

    fn accept(mut self) -> (TcpStateEnum<X>, Result<AcceptedTcpState<X>, AcceptError>) {
        let Some(child_key) = self.accept_queue.pop_front() else {
            return (self.into(), Err(AcceptError::NothingToAccept));
        };

        let child = self.remove_child(child_key).unwrap();

        // if the child is in an acceptable state, it's wrapped in an `AcceptedTcpState` and
        // returned to the caller
        let accepted_state = match child.try_into() {
            Ok(x) => x,
            Err(child) => {
                // the child is in a state that we can't return to the caller, so we messed up
                // somewhere earlier
                panic!("Unexpected child TCP state in accept queue: {:?}", child);
            }
        };

        (self.into(), Ok(accepted_state))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::NotConnected))
    }

    fn recv(self, _writer: impl Write, _len: usize) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        (self.into(), Err(RecvError::NotConnected))
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // In Linux there is conceptually the syn queue and the accept queue. When the application
        // calls `listen()`, it passes a `backlog` argument. The question is: does this backlog
        // apply to the syn queue, accept queue, or both? Some references[1] and the listen(2)[2]
        // man page say that the backlog only applies to the accept queue, but other blogs[3,4] and
        // stack overflow[5] say that it applies to both queues.
        //
        // The truth is probably more nuanced, and Linux technically doesn't have a "syn queue", but
        // this should be good enough for us. We'll apply the backlog as a limit to both queues
        // (each queue can hold `backlog` entries). In our case, the "syn queue" length is
        // `children.len() - accept_queue.len()`.
        //
        // If the accept queue is full, the application is slow at accept()ing new connections. As a
        // push-back mechanism drop all incoming SYN packets, and incoming ACK packets that are
        // intended for a child in the "syn-received" state (since they would then get added to the
        // accept queue, but the accept queue is full). If the syn queue is full, drop all incoming
        // SYN packets (we don't support SYN cookies). This seems to be along the lines of what
        // Linux does.[4]
        //
        // [1]: https://veithen.io/2014/01/01/how-tcp-backlog-works-in-linux.html
        // [2]: https://man7.org/linux/man-pages/man2/listen.2.html
        // [3]: https://arthurchiao.art/blog/tcp-listen-a-tale-of-two-queues/
        // [4]: https://blog.cloudflare.com/syn-packet-handling-in-the-wild/
        // [5]: https://stackoverflow.com/questions/58183847/

        let max_backlog = self.max_backlog.try_into().unwrap();
        let syn_queue_len = self
            .children
            .len()
            .checked_sub(self.accept_queue.len())
            .unwrap();
        let accept_queue_full = self.accept_queue.len() >= max_backlog;
        let syn_queue_full = syn_queue_len >= max_backlog;

        // if either queue is full, drop all SYN packets
        if header.flags.contains(TcpFlags::SYN) && (accept_queue_full || syn_queue_full) {
            return (self.into(), Ok(0));
        }

        let conn_addrs = RemoteLocalPair::new(header.src(), header.dst());

        // forward the packet to a child state if it's from a known src address
        if let Some(child_key) = self.conn_map.get(&conn_addrs) {
            // if in the "syn-received" state, is an ACK packet, and the accept queue is full, drop
            // the packet
            if matches!(self.child(*child_key), Some(TcpStateEnum::SynReceived(_)))
                && header.flags.contains(TcpFlags::ACK)
                && accept_queue_full
            {
                return (self.into(), Ok(0));
            }

            // forward the packet to the child state
            let rv = self
                .with_child(*child_key, |state| state.push_packet(header, payload))
                .unwrap();

            // propagate any error from the child to the caller
            return (self.into(), rv);
        }

        // this packet is meant for the listener, or for a child that no longer exists

        // drop non-SYN packets
        if !header.flags.contains(TcpFlags::SYN) {
            // it's either for an old child that no longer exists, or is for the listener and
            // doesn't have the SYN flag for some reason
            return (self.into(), Ok(0));
        }

        // we received a SYN packet, so register a new child in the "syn-received" state
        self.register_child(header, payload);

        (self.into(), Ok(0))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        if let Some(header) = self.send_buffer.pop_front() {
            return (self.into(), Ok((header, Payload::default())));
        }

        if let Some(child_key) = self.to_send.pop_front() {
            let rv = self
                .with_child(child_key, |state| state.pop_packet())
                .unwrap();

            // if the child was in the list, then we'll assume it must have a packet to send
            let (header, payload) = rv.unwrap();

            // might as well check this
            debug_assert!(payload.is_empty());

            return (self.into(), Ok((header, payload)));
        }

        (self.into(), Err(PopPacketError::NoPacket))
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::LISTENING;

        if !self.accept_queue.is_empty() {
            poll_state.insert(PollState::READY_TO_ACCEPT);
        }

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        !self.send_buffer.is_empty() || !self.to_send.is_empty()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        None
    }
}

impl<X: Dependencies> SynSentState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        let state = SynSentState { common, connection };

        // if still in the "syn-sent" state after 60 seconds, close it
        let timeout = state.common.current_time() + X::Duration::from_secs(60);
        state.common.register_timer(timeout, |state| {
            if let TcpStateEnum::SynSent(mut state) = state {
                state.common.error = Some(TcpError::TimedOut);

                let (state, rv) = state.rst_close();
                assert!(rv.is_ok());
                state
            } else {
                state
            }
        });

        state
    }
}

impl<X: Dependencies> TcpStateTrait<X> for SynSentState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        // we haven't received a SYN yet, so we can't have received data and don't
        // need to send an RST
        debug_assert!(!self.connection.recv_buf_has_data());

        self.common
            .set_error_if_unset(TcpError::ClosedWhileConnecting);

        let new_state = ClosedState::new(self.common, None, /* was_connected= */ true);
        (new_state.into(), Ok(()))
    }

    fn rst_close(mut self) -> (TcpStateEnum<X>, Result<(), RstCloseError>) {
        // we haven't received a SYN yet, so we can't have received data and don't
        // need to send an RST
        debug_assert!(!self.connection.recv_buf_has_data());

        self.common
            .set_error_if_unset(TcpError::ClosedWhileConnecting);

        let new_state = ClosedState::new(self.common, None, /* was_connected= */ true);
        (new_state.into(), Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we haven't received a SYN yet, so we can't have received data and don't
            // need to send an RST
            debug_assert!(!self.connection.recv_buf_has_data());

            self.common
                .set_error_if_unset(TcpError::ClosedWhileConnecting);

            let new_state = ClosedState::new(self.common, None, /* was_connected= */ true);
            return (new_state.into(), Ok(()));
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::InProgress))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::NotConnected))
    }

    fn recv(self, _writer: impl Write, _len: usize) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        (self.into(), Err(RecvError::NotConnected))
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received SYN and ACK (active open), move to the "established" state
        if self.connection.received_syn() && self.connection.syn_was_acked() {
            let new_state = EstablishedState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        // if received SYN and no ACK (simultaneous open), move to the "syn-received" state
        if self.connection.received_syn() {
            let new_state = SynReceivedState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        // TODO: unsure what to do otherwise; just dropping the packet

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTING;

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> SynReceivedState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        let state = SynReceivedState { common, connection };

        // if still in the "syn-received" state after 60 seconds, close it with a RST
        let timeout = state.common.current_time() + X::Duration::from_secs(60);
        state.common.register_timer(timeout, |state| {
            if let TcpStateEnum::SynReceived(mut state) = state {
                state.common.error = Some(TcpError::TimedOut);

                let (state, rv) = state.rst_close();
                assert!(rv.is_ok());
                return state;
            }

            state
        });

        state
    }
}

impl<X: Dependencies> TcpStateTrait<X> for SynReceivedState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // send a FIN packet
            self.connection.send_fin();

            self.common
                .set_error_if_unset(TcpError::ClosedWhileConnecting);

            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            FinWaitOneState::new(self.common, self.connection).into()
        };

        (new_state, Ok(()))
    }

    fn rst_close(self) -> (TcpStateEnum<X>, Result<(), RstCloseError>) {
        let new_state = reset_connection(self.common, self.connection);
        (new_state.into(), Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // send a FIN packet
            self.connection.send_fin();

            self.common
                .set_error_if_unset(TcpError::ClosedWhileConnecting);

            let new_state = FinWaitOneState::new(self.common, self.connection);
            return (new_state.into(), Ok(()));
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::InProgress))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::NotConnected))
    }

    fn recv(self, _writer: impl Write, _len: usize) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        (self.into(), Err(RecvError::NotConnected))
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // waiting for the ACK for our SYN

        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received ACK, move to the "established" state
        if self.connection.syn_was_acked() {
            let new_state = EstablishedState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTING;

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> EstablishedState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        EstablishedState { common, connection }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for EstablishedState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // send a FIN packet
            self.connection.send_fin();

            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            FinWaitOneState::new(self.common, self.connection).into()
        };

        (new_state, Ok(()))
    }

    fn rst_close(self) -> (TcpStateEnum<X>, Result<(), RstCloseError>) {
        let new_state = reset_connection(self.common, self.connection);
        (new_state.into(), Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // send a FIN packet
            self.connection.send_fin();

            let new_state = FinWaitOneState::new(self.common, self.connection);
            return (new_state.into(), Ok(()));
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(
        mut self,
        reader: impl Read,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        let rv = self.connection.send(reader, len);
        (self.into(), rv)
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);
        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received FIN, move to the "close-wait" state
        if self.connection.received_fin() {
            let new_state = CloseWaitState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        if self.connection.send_buf_has_space() {
            poll_state.insert(PollState::WRITABLE);
        }

        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> FinWaitOneState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        FinWaitOneState { common, connection }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for FinWaitOneState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            // we're already in the process of closing (active close)
            self.into()
        };

        (new_state, Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing (active close)
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::StreamClosed))
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);
        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received FIN and ACK, move to the "time-wait" state
        if self.connection.received_fin() && self.connection.fin_was_acked() {
            let new_state = TimeWaitState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        // if received FIN, move to the "closing" state
        if self.connection.received_fin() {
            let new_state = ClosingState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        // if received ACK, move to the "fin-wait-two" state
        if self.connection.fin_was_acked() {
            let new_state = FinWaitTwoState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        // we've sent a FIN
        poll_state.insert(PollState::SEND_CLOSED);
        assert!(!poll_state.contains(PollState::WRITABLE));

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> FinWaitTwoState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        FinWaitTwoState { common, connection }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for FinWaitTwoState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            // we're already in the process of closing (active close)
            self.into()
        };

        (new_state, Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing (active close)
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::StreamClosed))
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);
        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received FIN, move to the "time-wait" state
        if self.connection.received_fin() {
            let new_state = TimeWaitState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        // we've sent a FIN
        poll_state.insert(PollState::SEND_CLOSED);
        assert!(!poll_state.contains(PollState::WRITABLE));

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> ClosingState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        ClosingState { common, connection }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for ClosingState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            // we're already in the process of closing (active close)
            self.into()
        };

        (new_state, Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing (active close)
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::StreamClosed))
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);

        // the peer won't send any more data (it sent a FIN), so if there's no more data in the
        // buffer, inform the socket
        if matches!(rv, Err(RecvError::Empty)) {
            return (self.into(), Err(RecvError::StreamClosed));
        }

        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received ACK, move to the "time-wait" state
        if self.connection.fin_was_acked() {
            let new_state = TimeWaitState::new(self.common, self.connection);
            return (new_state.into(), Ok(pushed_len));
        }

        // drop all other packets

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        // we've received a FIN
        poll_state.insert(PollState::RECV_CLOSED);
        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        // we've sent a FIN
        poll_state.insert(PollState::SEND_CLOSED);
        assert!(!poll_state.contains(PollState::WRITABLE));

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> TimeWaitState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        let state = TimeWaitState { common, connection };

        // taken from /proc/sys/net/ipv4/tcp_fin_timeout
        let timeout = X::Duration::from_secs(60);

        // if still in the "time-wait" state after the timeout, close it
        let timeout = state.common.current_time() + timeout;
        state.common.register_timer(timeout, |state| {
            if let TcpStateEnum::TimeWait(state) = state {
                let recv_buffer = state.connection.into_recv_buffer();
                let new_state =
                    ClosedState::new(state.common, recv_buffer, /* was_connected= */ true);
                new_state.into()
            } else {
                state
            }
        });

        state
    }
}

impl<X: Dependencies> TcpStateTrait<X> for TimeWaitState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        // Linux does not seem to send a RST packet if a "time-wait" socket is closed while having
        // data in the receive buffer, probably because the peer should be in the "closed" state by
        // this point

        // if the connection receives any more data, it should send an RST
        self.connection.send_rst_if_recv_payload();

        // we're already in the process of closing (active close)
        (self.into(), Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing (active close)
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::StreamClosed))
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);

        // the peer won't send any more data (it sent a FIN), so if there's no more data in the
        // buffer, inform the socket
        if matches!(rv, Err(RecvError::Empty)) {
            return (self.into(), Err(RecvError::StreamClosed));
        }

        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        // TODO: send RST for all packets?
        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        // we've received a FIN
        poll_state.insert(PollState::RECV_CLOSED);
        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        // we've sent a FIN
        poll_state.insert(PollState::SEND_CLOSED);
        assert!(!poll_state.contains(PollState::WRITABLE));

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> CloseWaitState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        Self { common, connection }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for CloseWaitState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // send a FIN packet
            self.connection.send_fin();

            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            LastAckState::new(self.common, self.connection).into()
        };

        (new_state, Ok(()))
    }

    fn rst_close(self) -> (TcpStateEnum<X>, Result<(), RstCloseError>) {
        let new_state = reset_connection(self.common, self.connection);
        (new_state.into(), Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // send a FIN packet
            self.connection.send_fin();

            let new_state = LastAckState::new(self.common, self.connection);
            return (new_state.into(), Ok(()));
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(
        mut self,
        reader: impl Read,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        let rv = self.connection.send(reader, len);
        (self.into(), rv)
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);

        // the peer won't send any more data (it sent a FIN), so if there's no more data in the
        // buffer, inform the socket
        if matches!(rv, Err(RecvError::Empty)) {
            return (self.into(), Err(RecvError::StreamClosed));
        }

        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        if self.connection.send_buf_has_space() {
            poll_state.insert(PollState::WRITABLE);
        }

        // we've received a FIN
        poll_state.insert(PollState::RECV_CLOSED);
        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> LastAckState<X> {
    fn new(common: Common<X>, connection: Connection<X::Instant>) -> Self {
        Self { common, connection }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for LastAckState<X> {
    fn close(mut self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        let new_state = if self.connection.recv_buf_has_data() {
            // send a RST if there is still data in the receive buffer
            reset_connection(self.common, self.connection).into()
        } else {
            // if the connection receives any more data, it should send an RST
            self.connection.send_rst_if_recv_payload();

            // we're already in the process of closing (passive close)
            self.into()
        };

        (new_state, Ok(()))
    }

    fn shutdown(mut self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if how == Shutdown::Read || how == Shutdown::Both {
            self.connection.send_rst_if_recv_payload()
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing (passive close)
        }

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        (self.into(), Err(ConnectError::AlreadyConnected))
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        (self.into(), Err(SendError::StreamClosed))
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        let rv = self.connection.recv(writer, len);

        // the peer won't send any more data (it sent a FIN), so if there's no more data in the
        // buffer, inform the socket
        if matches!(rv, Err(RecvError::Empty)) {
            return (self.into(), Err(RecvError::StreamClosed));
        }

        (self.into(), rv)
    }

    fn push_packet(
        mut self,
        header: &TcpHeader,
        payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // make sure that the packet src/dst addresses are valid for this connection
        if !self.connection.packet_addrs_match(header) {
            // must drop the packet
            return (self.into(), Ok(0));
        }

        let pushed_len = match self.connection.push_packet(header, payload) {
            Ok(v) => v,
            Err(e) => return (self.into(), Err(e)),
        };

        // if the connection was reset
        if self.connection.is_reset() {
            if header.flags.contains(TcpFlags::RST) {
                self.common.set_error_if_unset(TcpError::ResetReceived);
            }

            let new_state = connection_was_reset(self.common, self.connection);
            return (new_state, Ok(pushed_len));
        }

        // if received ACK, move to the "closed" state
        if self.connection.fin_was_acked() {
            let recv_buffer = self.connection.into_recv_buffer();
            let new_state =
                ClosedState::new(self.common, recv_buffer, /* was_connected= */ true);
            return (new_state.into(), Ok(pushed_len));
        }

        (self.into(), Ok(pushed_len))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        let rv = self.connection.pop_packet(self.common.current_time());
        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CONNECTED;

        // we've received a FIN
        poll_state.insert(PollState::RECV_CLOSED);
        if self.connection.recv_buf_has_data() {
            poll_state.insert(PollState::READABLE);
        }

        // we've sent a FIN
        poll_state.insert(PollState::SEND_CLOSED);
        assert!(!poll_state.contains(PollState::WRITABLE));

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        self.connection.wants_to_send()
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        Some((self.connection.local_addr, self.connection.remote_addr))
    }
}

impl<X: Dependencies> RstState<X> {
    /// All packets must contain `TcpFlags::RST`.
    fn new(common: Common<X>, rst_packets: LinkedList<TcpHeader>, was_connected: bool) -> Self {
        debug_assert!(rst_packets.iter().all(|x| x.flags.contains(TcpFlags::RST)));
        assert!(!rst_packets.is_empty());

        Self {
            common,
            send_buffer: rst_packets,
            was_connected,
        }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for RstState<X> {
    fn close(self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        // we're already in the process of closing; do nothing
        (self.into(), Ok(()))
    }

    fn shutdown(self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if !self.was_connected {
            return (self.into(), Err(ShutdownError::NotConnected));
        }

        if how == Shutdown::Read || how == Shutdown::Both {
            // we've been reset, so nothing to do
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing; do nothing
        }

        // TODO: should we return an error or do nothing?

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        if self.was_connected {
            (self.into(), Err(ConnectError::AlreadyConnected))
        } else {
            (self.into(), Err(ConnectError::InvalidState))
        }
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        if self.was_connected {
            (self.into(), Err(SendError::StreamClosed))
        } else {
            (self.into(), Err(SendError::NotConnected))
        }
    }

    fn recv(self, _writer: impl Write, _len: usize) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        if self.was_connected {
            (self.into(), Err(RecvError::StreamClosed))
        } else {
            (self.into(), Err(RecvError::NotConnected))
        }
    }

    fn push_packet(
        self,
        _header: &TcpHeader,
        _payload: Payload,
    ) -> (TcpStateEnum<X>, Result<u32, PushPacketError>) {
        // do nothing; drop all packets received in this state
        (self.into(), Ok(0))
    }

    fn pop_packet(
        mut self,
    ) -> (
        TcpStateEnum<X>,
        Result<(TcpHeader, Payload), PopPacketError>,
    ) {
        // if we're in this state we must have a packet queued
        let header = self.send_buffer.pop_front().unwrap();
        let packet = (header, Payload::default());

        // we're only supposed to send RST packets in this state
        assert!(packet.0.flags.contains(TcpFlags::RST));

        // if we have no more packets to send
        if self.send_buffer.is_empty() {
            let new_state = ClosedState::new(
                self.common,
                None,
                /* was_connected= */ self.was_connected,
            );
            return (new_state.into(), Ok(packet));
        }

        (self.into(), Ok(packet))
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::RECV_CLOSED | PollState::SEND_CLOSED;

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        if self.was_connected {
            poll_state.insert(PollState::CONNECTED);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        // if we're in this state we must have a packet queued
        assert!(!self.send_buffer.is_empty());
        true
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        None
    }
}

impl<X: Dependencies> ClosedState<X> {
    fn new(common: Common<X>, recv_buffer: Option<RecvQueue>, was_connected: bool) -> Self {
        let recv_buffer = recv_buffer.unwrap_or_else(|| RecvQueue::new(Seq::new(0)));

        if !was_connected {
            assert!(recv_buffer.is_empty());
        }

        Self {
            common,
            recv_buffer,
            was_connected,
        }
    }
}

impl<X: Dependencies> TcpStateTrait<X> for ClosedState<X> {
    fn close(self) -> (TcpStateEnum<X>, Result<(), CloseError>) {
        // already closed; do nothing
        (self.into(), Ok(()))
    }

    fn shutdown(self, how: Shutdown) -> (TcpStateEnum<X>, Result<(), ShutdownError>) {
        if !self.was_connected {
            return (self.into(), Err(ShutdownError::NotConnected));
        }

        if how == Shutdown::Read || how == Shutdown::Both {
            // we've been reset, so nothing to do
        }

        if how == Shutdown::Write || how == Shutdown::Both {
            // we're already in the process of closing; do nothing
        }

        // TODO: should we return an error or do nothing?

        (self.into(), Ok(()))
    }

    fn connect<T, E>(
        self,
        _remote_addr: SocketAddrV4,
        _associate_fn: impl FnOnce() -> Result<(SocketAddrV4, T), E>,
    ) -> (TcpStateEnum<X>, Result<T, ConnectError<E>>) {
        if self.was_connected {
            (self.into(), Err(ConnectError::AlreadyConnected))
        } else {
            (self.into(), Err(ConnectError::InvalidState))
        }
    }

    fn send(self, _reader: impl Read, _len: usize) -> (TcpStateEnum<X>, Result<usize, SendError>) {
        if !self.was_connected {
            return (self.into(), Err(SendError::NotConnected));
        }

        (self.into(), Err(SendError::StreamClosed))
    }

    fn recv(
        mut self,
        writer: impl Write,
        len: usize,
    ) -> (TcpStateEnum<X>, Result<usize, RecvError>) {
        if !self.was_connected {
            return (self.into(), Err(RecvError::NotConnected));
        }

        if self.recv_buffer.is_empty() {
            return (self.into(), Err(RecvError::StreamClosed));
        }

        let rv = self.recv_buffer.read(writer, len).map_err(RecvError::Io);

        (self.into(), rv)
    }

    fn clear_error(&mut self) -> Option<TcpError> {
        self.common.error.take()
    }

    fn poll(&self) -> PollState {
        let mut poll_state = PollState::CLOSED;

        poll_state.insert(PollState::RECV_CLOSED);
        if !self.recv_buffer.is_empty() {
            poll_state.insert(PollState::READABLE);
        }

        poll_state.insert(PollState::SEND_CLOSED);
        assert!(!poll_state.contains(PollState::WRITABLE));

        if self.was_connected {
            poll_state.insert(PollState::CONNECTED);
        }

        if self.common.error.is_some() {
            poll_state.insert(PollState::ERROR);
        }

        poll_state
    }

    fn wants_to_send(&self) -> bool {
        false
    }

    fn local_remote_addrs(&self) -> Option<(SocketAddrV4, SocketAddrV4)> {
        None
    }
}

/// Reset the connection, get the resulting RST packet, and return a new `RstState` that will send
/// this RST packet.
fn reset_connection<X: Dependencies>(
    common: Common<X>,
    mut connection: Connection<X::Instant>,
) -> RstState<X> {
    connection.send_rst();

    let new_state = connection_was_reset(common, connection);

    let TcpStateEnum::Rst(new_state) = new_state else {
        panic!("We called `send_rst()` above but aren't now in the \"rst\" state: {new_state:?}");
    };

    new_state
}

/// For a connection that was reset (either by us or by the peer), check if it has a remaining RST
/// packet to send, and return a new `RstState` that will send this RST packet or a new
/// `ClosedState` if not.
fn connection_was_reset<X: Dependencies>(
    mut common: Common<X>,
    mut connection: Connection<X::Instant>,
) -> TcpStateEnum<X> {
    assert!(connection.is_reset());

    let now = common.current_time();

    // check if there's an RST packet to send
    if let Ok((header, payload)) = connection.pop_packet(now) {
        assert!(payload.is_empty());
        debug_assert!(connection.pop_packet(now).is_err());

        common.set_error_if_unset(TcpError::ResetSent);

        let rst_packets = [header].into_iter().collect();
        RstState::new(common, rst_packets, /* was_connected= */ true).into()
    } else {
        // the receive buffer is cleared when a connection is reset, which is why we pass `None`
        ClosedState::new(common, None, /* was_connected= */ true).into()
    }
}