emissary-core 0.4.0

Rust implementation of the I2P protocol stack
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
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
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use crate::{
    crypto::{base32_decode, base32_encode, base64_encode, sha256::Sha256, SigningPrivateKey},
    destination::{DeliveryStyle, Destination, DestinationEvent, LeaseSetStatus},
    error::QueryError,
    events::EventHandle,
    i2cp::{I2cpPayload, I2cpPayloadBuilder},
    primitives::{Destination as Dest, DestinationId, LeaseSet2, LeaseSet2Header, Mapping},
    protocol::Protocol,
    runtime::{AddressBook, JoinSet, Runtime},
    sam::{
        parser::{DestinationContext, SamCommand, SessionKind},
        pending::session::SamSessionContext,
        protocol::{
            datagram::DatagramManager,
            streaming::{Direction, ListenerKind, StreamManager, StreamManagerEvent},
        },
        socket::SamSocket,
        types::{
            PendingSession, PendingSessionState, PublicKeyContext, SamSessionCommand,
            SamSessionCommandRecycle, SamSessionKind,
        },
        SubSessionCommand,
    },
};

use bytes::{BufMut, Bytes, BytesMut};
use futures::StreamExt;
use hashbrown::HashMap;
use thingbuf::mpsc::{Receiver, Sender};

use alloc::{
    boxed::Box,
    format,
    string::{String, ToString},
    sync::Arc,
    vec,
    vec::Vec,
};
use core::{
    future::Future,
    pin::Pin,
    task::{Context, Poll, Waker},
    time::Duration,
};

/// Logging target for the file.
const LOG_TARGET: &str = "emissary::sam::session";

/// Active SAMv3 session.
pub struct SamSession<R: Runtime> {
    /// Address book.
    address_book: Option<Arc<dyn AddressBook>>,

    /// I2P datagram manager.
    datagram_manager: DatagramManager<R>,

    /// [`Dest`] of the session.
    ///
    /// Used to create new lease sets.
    dest: Dest,

    /// [`Destination`] of the session.
    destination: Destination<R>,

    /// Event handle.
    #[allow(unused)]
    event_handle: EventHandle<R>,

    /// Pending host lookups
    lookup_futures: R::JoinSet<(String, Option<String>)>,

    /// Session options.
    options: HashMap<String, String>,

    /// Pending host lookups.
    ///
    /// Pending `NAMING LOOKUP` queries for `.b32.i2p` addresses are stored here
    /// while the corresponding lease set is being queried.
    pending_host_lookups: HashMap<DestinationId, String>,

    /// Pending outbound sessions.
    ///
    /// `STREAM CONNECT` is marked pending if there is no active lease set for the remote
    /// destination. The stream is moved from pending to active/rejected, based on the lease set
    /// query result. The stream is also set into pending state even if a lease set is found,
    /// for the duration of the handshake process and if the remote doesn't answer any of the three
    /// `SYN` messages that are sent, the stream is destroyed.
    ///
    /// If a datagram is sent to a remote destination whose lease set is not available, the session
    /// is marked as pending until the lease set is found and all datagrams sent while the lease
    /// set is being queried are stored in the pending session state.
    pending_outbound: HashMap<DestinationId, PendingSession<R>>,

    /// Public key context for the session.
    public_key_context: PublicKeyContext,

    /// Receiver for commands sent for this session.
    ///
    /// Commands are dispatched by `SamServer` which ensures that [`SamCommand::CreateSession`]
    /// is never received by an active session.
    receiver: Receiver<SamSessionCommand<R>, SamSessionCommandRecycle>,

    /// Session ID.
    session_id: Arc<str>,

    /// Session kind.
    session_kind: SamSessionKind,

    /// Signing key.
    signing_key: SigningPrivateKey,

    /// Socket for reading session-related commands from the client.
    ///
    /// Set to `None` after the socket has been closed and th session is being destroyed.
    socket: Option<Box<SamSocket<R>>>,

    /// I2P virtual stream manager.
    stream_manager: StreamManager<R>,

    /// TX channel for sending session IDs of sub-sessions to `SamServer`
    ///
    /// `None` if `session_kind` is not `SessionKind::Primary`.
    sub_session_tx: Option<Sender<SubSessionCommand>>,

    /// Waker.
    waker: Option<Waker>,
}

impl<R: Runtime> SamSession<R> {
    /// Create new [`SamSession`].
    pub fn new(context: SamSessionContext<R>) -> Self {
        let SamSessionContext {
            address_book,
            datagram_tx,
            destination,
            event_handle,
            inbound,
            mut socket,
            netdb_handle,
            options,
            outbound,
            profile_storage,
            receiver,
            session_id,
            session_kind,
            sub_session_tx,
            tunnel_pool_handle,
        } = context;

        let (session_destination, dest, privkey, public_key_context, signing_key) = {
            let DestinationContext {
                destination,
                private_key,
                signing_key,
            } = destination;
            let destination_id = destination.id();

            // from specification:
            //
            // "The $privkey is the base 64 of the concatenation of the Destination followed by the
            // Private Key followed by the Signing Private Key, optionally followed by the Offline
            // Signature, which is 663 or more bytes in binary and 884 or more bytes in base 64,
            // depending on signature type. The binary format is specified in Private Key File."
            let privkey = {
                let mut out = BytesMut::with_capacity(destination.serialized_len() + 2 * 32);
                out.put_slice(&destination.serialize());
                out.put_slice((*private_key).as_ref());
                out.put_slice((*signing_key).as_ref());

                base64_encode(out)
            };

            // create public key context for the session.
            let public_key_context = PublicKeyContext::new::<R>(&options);

            // create leaseset for the destination and store it in `NetDb`
            let is_unpublished = options
                .get("i2cp.dontPublishLeaseSet")
                .map(|value| value.parse::<bool>().unwrap_or(false))
                .unwrap_or(false);

            let local_leaseset = Bytes::from(
                LeaseSet2 {
                    header: LeaseSet2Header {
                        destination: destination.clone(),
                        expires: Duration::from_secs(10 * 60).as_secs() as u32,
                        is_unpublished,
                        offline_signature: None,
                        published: R::time_since_epoch().as_secs() as u32,
                    },
                    public_keys: public_key_context.public_keys(),
                    leases: inbound.values().cloned().collect(),
                }
                .serialize(&signing_key),
            );

            // publish the new destination to the event system
            if is_unpublished {
                event_handle.client_destination_started(session_id.to_string());
            } else {
                event_handle.server_destination_started(
                    session_id.to_string(),
                    base32_encode(destination_id.to_vec()),
                );
            }

            let mut session_destination = Destination::new(
                destination_id.clone(),
                public_key_context.private_key(),
                public_key_context.public_keys(),
                local_leaseset.clone(),
                netdb_handle,
                tunnel_pool_handle,
                outbound.into_iter().collect(),
                inbound.into_values().collect(),
                is_unpublished,
                profile_storage,
            );
            // TODO: not needed anymore?
            session_destination.publish_lease_set(local_leaseset.clone());

            tracing::info!(
                target: LOG_TARGET,
                %session_id,
                %destination_id,
                "start active session",
            );

            (
                session_destination,
                destination,
                privkey,
                public_key_context,
                signing_key,
            )
        };

        socket.send_message(
            format!("SESSION STATUS RESULT=OK DESTINATION={privkey}\n").as_bytes().to_vec(),
        );

        Self {
            address_book,
            datagram_manager: DatagramManager::new(
                dest.clone(),
                datagram_tx,
                options.clone(),
                *signing_key.clone(),
            ),
            dest: dest.clone(),
            destination: session_destination,
            public_key_context,
            event_handle,
            lookup_futures: R::join_set(),
            options,
            pending_host_lookups: HashMap::new(),
            pending_outbound: HashMap::new(),
            receiver,
            session_id,
            session_kind: match session_kind {
                SessionKind::Stream => SamSessionKind::Stream,
                SessionKind::Datagram => SamSessionKind::Datagram {
                    kind: SessionKind::Datagram,
                },
                SessionKind::Anonymous => SamSessionKind::Datagram {
                    kind: SessionKind::Anonymous,
                },
                SessionKind::Datagram2 => SamSessionKind::Datagram {
                    kind: SessionKind::Datagram2,
                },
                SessionKind::Primary => SamSessionKind::Primary {
                    sub_sessions: HashMap::new(),
                },
            },
            signing_key: *signing_key.clone(),
            socket: Some(socket),
            stream_manager: StreamManager::new(dest, *signing_key),
            sub_session_tx,
            waker: None,
        }
    }

    /// Create outbound stream for a remote destiantion who's lease set has been resolved.
    ///
    /// The stream is considered pending and it's acceptance contingent on the remote destination
    /// responding to us within a reasonable time frame.
    fn create_outbound_stream(
        &mut self,
        destination_id: DestinationId,
        socket: Box<SamSocket<R>>,
        options: HashMap<String, String>,
    ) {
        let handle = self.destination.routing_path_handle(destination_id.clone());
        let (stream_id, packet, delivery_style, src_port, dst_port) = self
            .stream_manager
            .create_stream(destination_id.clone(), handle, socket, options);

        tracing::trace!(
            target: LOG_TARGET,
            %destination_id,
            ?stream_id,
            ?src_port,
            ?dst_port,
            "create pending outbound stream",
        );

        // mark the stream as pending & waiting for session to be opened
        //
        // from now on `StreamManager` will drive forward the stream progress and will
        // emit an event when the stream opens/fails to open
        self.pending_outbound
            .entry(destination_id.clone())
            .or_insert(PendingSession::<R>::new())
            .streams
            .push(PendingSessionState::AwaitingSession { stream_id });

        let Some(message) = I2cpPayloadBuilder::<R>::new(&packet)
            .with_protocol(Protocol::Streaming)
            .with_source_port(src_port)
            .with_destination_port(dst_port)
            .build()
        else {
            tracing::error!(
                target: LOG_TARGET,
                session_id = ?self.session_id,
                "failed to create i2cp payload",
            );
            debug_assert!(false);
            return;
        };

        if let Err(error) = self.destination.send_message(delivery_style, message) {
            tracing::error!(
                target: LOG_TARGET,
                session_id = ?self.session_id,
                ?error,
                "failed to send message to remote peer",
            );
            debug_assert!(false);
        }
    }

    /// Handle `STREAM CONNECT`.
    fn on_stream_connect(
        &mut self,
        mut socket: Box<SamSocket<R>>,
        destination_id: DestinationId,
        options: HashMap<String, String>,
        session_id: Arc<str>,
    ) {
        if !self.session_kind.supports_streams(&session_id) {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                stream_kind = ?self.session_kind,
                "session style doesn't support streams",
            );

            return drop(socket);
        };

        if destination_id == self.dest.id() {
            tracing::warn!(
                target: LOG_TARGET,
                "tried to open connection to self",
            );

            R::spawn(async move {
                let _ = socket
                    .send_message_blocking(b"STREAM STATUS RESULT=CANT_REACH_PEER\n".to_vec())
                    .await;
            });
            return;
        }

        tracing::info!(
            target: LOG_TARGET,
            session_id = %self.session_id,
            destination_id = %destination_id,
            "connect to destination",
        );

        match self.destination.query_lease_set(&destination_id) {
            LeaseSetStatus::Found => {
                tracing::trace!(
                    target: LOG_TARGET,
                    session_id = ?self.session_id,
                    %destination_id,
                    "lease set found, create outbound stream",
                );

                self.create_outbound_stream(destination_id, socket, options);
            }
            status @ (LeaseSetStatus::NotFound | LeaseSetStatus::Pending) => {
                tracing::trace!(
                    target: LOG_TARGET,
                    session_id = %self.session_id,
                    %destination_id,
                    ?status,
                    "lease set query started or pending, mark outbound stream as pending",
                );

                self.pending_outbound
                    .entry(destination_id.clone())
                    .or_insert(PendingSession::<R>::new())
                    .streams
                    .push(PendingSessionState::AwaitingLeaseSet { socket, options });
            }
        }
    }

    /// Handle `STREAM ACCEPT` command.
    ///
    /// Register the socket as an active listener to [`StreamManager`].
    ///
    /// If the session wasn't configured to use streams, reject the accept request.
    fn on_stream_accept(
        &mut self,
        socket: Box<SamSocket<R>>,
        options: HashMap<String, String>,
        session_id: Arc<str>,
    ) {
        if !self.session_kind.supports_streams(&session_id) {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                stream_kind = ?self.session_kind,
                "session style doesn't support streams",
            );

            return drop(socket);
        };

        if let Err(error) = self.stream_manager.register_listener(ListenerKind::Ephemeral {
            pending_routing_path_handle: self.destination.pending_routing_path_handle(),
            socket,
            silent: options
                .get("SILENT")
                .is_some_and(|value| value.parse::<bool>().unwrap_or(false)),
        }) {
            tracing::warn!(
                target: LOG_TARGET,
                ?error,
                session_id = %self.session_id,
                "failed to register ephemeral listener",
            );
        }
    }

    /// Handle `STREAM FORWARD` command.
    ///
    /// Register the socket as an active listener to [`StreamManager`].
    ///
    /// If the session wasn't configured to use streams, reject the forward request.
    fn on_stream_forward(
        &mut self,
        socket: Box<SamSocket<R>>,
        port: u16,
        options: HashMap<String, String>,
        session_id: Arc<str>,
    ) {
        if !self.session_kind.supports_streams(&session_id) {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                stream_kind = ?self.session_kind,
                "session style doesn't support streams",
            );

            return drop(socket);
        };

        if let Err(error) = self.stream_manager.register_listener(ListenerKind::Persistent {
            pending_routing_path_handle: self.destination.pending_routing_path_handle(),
            socket,
            port,
            silent: options
                .get("SILENT")
                .is_some_and(|value| value.parse::<bool>().unwrap_or(false)),
        }) {
            tracing::warn!(
                target: LOG_TARGET,
                ?error,
                session_id = %self.session_id,
                "failed to register persistent listener",
            );
        }
    }

    /// Send datagram to destination.
    ///
    /// If the session wasn't configured to use streams, the datagram is dropped.
    fn on_send_datagram(
        &mut self,
        destination: Dest,
        datagram: Vec<u8>,
        session_id: Arc<str>,
        options: Option<Mapping>,
    ) {
        if !self.session_kind.supports_datagrams(&session_id) {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                stream_kind = ?self.session_kind,
                "session style doesn't support datagrams",
            );
            return;
        }

        tracing::info!(
            target: LOG_TARGET,
            session_id = %self.session_id,
            destination_id = %destination.id(),
            style = ?self.session_kind,
            "send datagram",
        );
        let destination_id = destination.id();
        let protocol = self.session_kind.as_protocol(&session_id);

        match self.destination.query_lease_set(&destination_id) {
            LeaseSetStatus::Found => {
                let datagram = match protocol {
                    Protocol::Anonymous => self.datagram_manager.make_anonymous(datagram),
                    Protocol::Datagram => self.datagram_manager.make_datagram(datagram),
                    Protocol::Datagram2 => self.datagram_manager.make_datagram2(
                        datagram,
                        &Sha256::new().update(destination.as_ref()).finalize(),
                        options,
                    ),
                    Protocol::Streaming => unreachable!(),
                };

                if let Some(message) =
                    I2cpPayloadBuilder::<R>::new(&datagram).with_protocol(protocol).build()
                {
                    if let Err(error) = self
                        .destination
                        .send_message(DeliveryStyle::Unspecified { destination_id }, message)
                    {
                        tracing::warn!(
                            target: LOG_TARGET,
                            session_id = %self.session_id,
                            destination_id = %destination.id(),
                            ?error,
                            "failed to send repliable datagram",
                        )
                    }
                };
            }
            LeaseSetStatus::NotFound => {
                tracing::trace!(
                    target: LOG_TARGET,
                    session_id = %self.session_id,
                    %destination_id,
                    "lease set query started, mark outbound datagram as pending",
                );

                match self.pending_outbound.get_mut(&destination_id) {
                    Some(PendingSession { datagrams, .. }) => match datagrams {
                        None => {
                            *datagrams = Some((destination, vec![(protocol, datagram, options)]));
                        }
                        Some((_, datagrams)) => datagrams.push((protocol, datagram, options)),
                    },
                    None => {
                        self.pending_outbound.insert(
                            destination_id,
                            PendingSession {
                                streams: Vec::new(),
                                datagrams: Some((destination, vec![(protocol, datagram, options)])),
                            },
                        );
                    }
                }
            }
            LeaseSetStatus::Pending => {
                tracing::warn!(
                    target: LOG_TARGET,
                    session_id = %self.session_id,
                    %destination_id,
                    "received datagram while session was pending",
                );

                match self.pending_outbound.get_mut(&destination_id) {
                    Some(PendingSession { datagrams, .. }) => match datagrams {
                        None => {
                            *datagrams = Some((destination, vec![(protocol, datagram, options)]));
                        }
                        Some((_, datagrams)) => datagrams.push((protocol, datagram, options)),
                    },
                    None => {
                        self.pending_outbound.insert(
                            destination_id,
                            PendingSession {
                                streams: Vec::new(),
                                datagrams: Some((destination, vec![(protocol, datagram, options)])),
                            },
                        );
                    }
                }
            }
        }
    }

    /// Handle succeeded lease set query result.
    ///
    /// For each of the pending streams, create a new outbound stream which allocates context in
    /// [`StreamManger`] for it and creates a `SYN` packet which is sent sent in an NS message to
    /// remote destination.
    ///
    /// Same deal for datagrams: send all pending datagrams to remote destination in NS messages.
    ///
    /// All pending host lookups are also resolved with a success and the destination of the remote
    /// peer is sent via the active socket to client.
    fn on_lease_set_found(&mut self, destination_id: DestinationId) {
        tracing::trace!(
            target: LOG_TARGET,
            session_id = %self.session_id,
            %destination_id,
            "lease set found",
        );

        if let Some(PendingSession { streams, datagrams }) =
            self.pending_outbound.remove(&destination_id)
        {
            streams.into_iter().for_each(|state| match state {
                PendingSessionState::AwaitingLeaseSet { socket, options } => {
                    self.create_outbound_stream(destination_id.clone(), socket, options);
                }
                PendingSessionState::AwaitingSession { .. } => {
                    // new stream was opened but by the the time the initial `SYN` packet was sent,
                    // remote's lease set had expired and they had not sent us, a new lease set a
                    // lease set query was started and the lease set was found
                    //
                    // the new lease set can be ignored for `PendingSessionState::AwaitinSession`
                    // since the `SYN` packet was queued in `Destination` and
                    // was sent to remote destination when the lease set was
                    // received
                }
            });

            if let Some((destination, datagrams)) = datagrams {
                datagrams.into_iter().for_each(|(protocol, datagram, options)| {
                    let datagram = match protocol {
                        Protocol::Anonymous => self.datagram_manager.make_anonymous(datagram),
                        Protocol::Datagram => self.datagram_manager.make_datagram(datagram),
                        Protocol::Datagram2 => self.datagram_manager.make_datagram2(
                            datagram,
                            &Sha256::new().update(destination.as_ref()).finalize(),
                            options,
                        ),
                        Protocol::Streaming => unreachable!(),
                    };

                    if let Some(message) =
                        I2cpPayloadBuilder::<R>::new(&datagram).with_protocol(protocol).build()
                    {
                        if let Err(error) = self.destination.send_message(
                            DeliveryStyle::Unspecified {
                                destination_id: destination_id.clone(),
                            },
                            message,
                        ) {
                            tracing::warn!(
                                target: LOG_TARGET,
                                session_id = %self.session_id,
                                destination_id = %destination.id(),
                                ?error,
                                "failed to send repliable datagram",
                            )
                        }
                    };
                });
            }
        } else {
            tracing::debug!(
                target: LOG_TARGET,
                session_id = ?self.session_id,
                %destination_id,
                "lease set query succeeded but no stream is interested in the lease set",
            );
        }

        if let Some(name) = self.pending_host_lookups.remove(&destination_id) {
            tracing::trace!(
                target: LOG_TARGET,
                session_id = ?self.session_id,
                %destination_id,
                ?name,
                "lease set query succeeded for pending host lookup",
            );

            if let Some(socket) = &mut self.socket {
                socket.send_message(
                    format!(
                        "NAMING REPLY RESULT=OK NAME={name} VALUE={}\n",
                        base64_encode(
                            self.destination
                                .lease_set(&destination_id)
                                .header
                                .destination
                                .serialized()
                        ),
                    )
                    .as_bytes()
                    .to_vec(),
                );

                if let Some(waker) = self.waker.take() {
                    waker.wake_by_ref();
                }
            }
        }
    }

    /// Handle lease set query error for `destination_id`.
    ///
    /// Lease set query can fail for either streams, datagrams or a host lookup, either one of them,
    /// some of them all or all of them at the same time, depending on what kind protocol is being
    /// used.
    ///
    /// Any pending datagrams for the unreachable destiantion are discarded, an error is sent to the
    /// user on each of the active stream and if there are pending host lookups, the client is
    /// notified of the error via the open socket
    fn on_lease_set_not_found(&mut self, destination_id: DestinationId, error: QueryError) {
        tracing::trace!(
            target: LOG_TARGET,
            session_id = %self.session_id,
            %destination_id,
            ?error,
            "lease set not found",
        );

        if let Some(PendingSession { streams, datagrams }) =
            self.pending_outbound.remove(&destination_id)
        {
            if let Some((_, datagrams)) = datagrams {
                tracing::debug!(
                    target: LOG_TARGET,
                    %destination_id,
                    num_datagrams = ?datagrams.len(),
                    "discarding pending datagrams, lease set not found",
                );
            }

            let sockets = streams
                .into_iter()
                .filter_map(|state| match state {
                    PendingSessionState::AwaitingLeaseSet { socket, .. } => {
                        tracing::warn!(
                            target: LOG_TARGET,
                            session_id = ?self.session_id,
                            %destination_id,
                            ?error,
                            "unable to open stream, lease set not found",
                        );

                        Some(socket)
                    }
                    PendingSessionState::AwaitingSession { stream_id } => {
                        // new stream was opened but by the the time the initial `SYN` packet was
                        // sent, remote's lease set had expired and they had
                        // not sent us, a new lease set a lease
                        // set query was started but the lease set was not found in the netdb
                        //
                        // as the remote cannot be contacted, remove the pending stream from
                        // `StreamManager`
                        tracing::warn!(
                            target: LOG_TARGET,
                            session_id = ?self.session_id,
                            %destination_id,
                            ?stream_id,
                            "stream awaiting session but remote lease set not found",
                        );

                        self.stream_manager.remove_session(&destination_id);
                        None
                    }
                })
                .collect::<Vec<_>>();

            if !sockets.is_empty() {
                R::spawn(async move {
                    for mut socket in sockets {
                        let _ = socket
                            .send_message_blocking(b"STREAM STATUS RESULT=CANT_REACH_PEER".to_vec())
                            .await;
                    }
                });
            }
        } else {
            tracing::debug!(
                target: LOG_TARGET,
                session_id = ?self.session_id,
                %destination_id,
                ?error,
                "lease set query failure but no stream is interested in the lease set",
            );
        }

        if let Some(name) = self.pending_host_lookups.remove(&destination_id) {
            tracing::debug!(
                target: LOG_TARGET,
                session_id = ?self.session_id,
                %destination_id,
                ?name,
                ?error,
                "lease set query failed for pending host lookup",
            );

            if let Some(socket) = &mut self.socket {
                socket.send_message(
                    format!("NAMING REPLY RESULT=KEY_NOT_FOUND NAME={name}\n").as_bytes().to_vec(),
                );

                if let Some(waker) = self.waker.take() {
                    waker.wake_by_ref();
                }
            }
        }
    }

    /// Handle one or more inbound messages.
    fn on_inbound_message(&mut self, messages: Vec<Vec<u8>>) {
        messages
            .into_iter()
            .for_each(|message| match I2cpPayload::decompress::<R>(message) {
                Some(payload) => {
                    tracing::trace!(
                        target: LOG_TARGET,
                        session_id = %self.session_id,
                        src_port = ?payload.src_port,
                        dst_port = ?payload.dst_port,
                        protocol = ?payload.protocol,
                        "handle protocol payload",
                    );

                    match payload.protocol {
                        Protocol::Streaming => {
                            if let Err(error) = self.stream_manager.on_packet(payload) {
                                tracing::warn!(
                                    target: LOG_TARGET,
                                    session_id = ?self.session_id,
                                    ?error,
                                    "failed to handle streaming protocol packet",
                                );
                            }
                        }
                        protocol =>
                            if let Err(error) = self.datagram_manager.on_datagram(payload) {
                                tracing::warn!(
                                    target: LOG_TARGET,
                                    session_id = ?self.session_id,
                                    ?protocol,
                                    ?error,
                                    "failed to handle datagram",
                                );
                            },
                    }
                }
                None => tracing::warn!(
                    target: LOG_TARGET,
                    session_id = ?self.session_id,
                    "failed to decompress i2cp payload",
                ),
            })
    }

    /// Handle `NAMING LOOKUP` query from the client.
    ///
    /// The query can either be for `ME`, meaning the [`Destination`] of [`SamSession`] is returned,
    /// a `.b32.i2p` which starts a lease set query for the destination. or a `.i2p` host name which
    /// is looked up from an address book if it exists.
    ///
    /// For `.b32.i2p`/`.i2p`, naming reply is deferred until the query is finished.
    fn on_naming_lookup(&mut self, name: String) {
        if name.as_str() == "ME" {
            tracing::debug!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                "naming lookup for self",
            );

            if let Some(socket) = &mut self.socket {
                socket.send_message(
                    format!(
                        "NAMING REPLY RESULT=OK NAME=ME VALUE={}\n",
                        base64_encode(self.dest.serialized())
                    )
                    .as_bytes()
                    .to_vec(),
                );
            }

            return;
        }

        // if the host name ends in `.b32.i2p`, validate the hostname and check if [`Destination`]
        // already holds the host's lease set and if not, start a query
        //
        // once the query finishes, the naming reply is sent to client
        if let Some(end) = name.find(".b32.i2p") {
            tracing::debug!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                "naming lookup for .b32.i2p address",
            );

            let start = if name.starts_with("http://") {
                7usize
            } else if name.starts_with("https://") {
                8usize
            } else {
                0usize
            };

            let message = match base32_decode(&name[start..end]) {
                None => {
                    tracing::warn!(
                        target: LOG_TARGET,
                        session_id = %self.session_id,
                        ?name,
                        "invalid .b32.i2p address",
                    );

                    Some(
                        format!("NAMING REPLY RESULT=INVALID_KEY NAME={name}\n")
                            .as_bytes()
                            .to_vec(),
                    )
                }
                Some(destination) => {
                    let destination_id = DestinationId::from(destination);

                    match self.destination.query_lease_set(&destination_id) {
                        LeaseSetStatus::Found => {
                            tracing::trace!(
                                target: LOG_TARGET,
                                session_id = %self.session_id,
                                %destination_id,
                                ?name,
                                "lease set found for host",
                            );

                            Some(
                                format!(
                                    "NAMING REPLY RESULT=OK NAME={name} VALUE={}\n",
                                    base64_encode(
                                        self.destination
                                            .lease_set(&destination_id)
                                            .header
                                            .destination
                                            .serialized()
                                    )
                                )
                                .as_bytes()
                                .to_vec(),
                            )
                        }
                        status => {
                            tracing::trace!(
                                target: LOG_TARGET,
                                session_id = %self.session_id,
                                %destination_id,
                                ?name,
                                ?status,
                                "lease set not found for host, query started",
                            );
                            self.pending_host_lookups.insert(destination_id, name);

                            None
                        }
                    }
                }
            };

            if let (Some(socket), Some(message)) = (&mut self.socket, message) {
                socket.send_message(message);
            }

            return;
        }

        let message = match name.find(".i2p") {
            None => {
                tracing::warn!(
                    target: LOG_TARGET,
                    session_id = %self.session_id,
                    ?name,
                    "invalid host name",
                );

                Some(format!("NAMING REPLY RESULT=INVALID_KEY NAME={name}\n").as_bytes().to_vec())
            }
            Some(_) => match &self.address_book {
                None => {
                    tracing::warn!(
                        target: LOG_TARGET,
                        session_id = %self.session_id,
                        ?name,
                        "address book doesn't exist",
                    );

                    Some(
                        format!("NAMING REPLY RESULT=KEY_NOT_FOUND NAME={name}\n")
                            .as_bytes()
                            .to_vec(),
                    )
                }
                Some(address_book) => {
                    tracing::debug!(
                        target: LOG_TARGET,
                        ?name,
                        "lookup name from address book",
                    );

                    let future = address_book.resolve_base64(name.clone());
                    self.lookup_futures.push(async move { (name, future.await) });

                    None
                }
            },
        };

        if let (Some(socket), Some(message)) = (&mut self.socket, message) {
            socket.send_message(message);
        }
    }

    /// Attempt to create new sub-session.
    ///
    /// The sub-session is rejected if [`SamSessionKind`] is not `Primary`, if there already exists
    /// a sub-session with the same session ID or if [`SamServer`] fails to send the sub-session ->
    /// primary session ID mapping to [`SamServer`].
    ///
    /// On success, the sub-session ID is added to the list of sub-sessions the primary session has.
    ///
    /// Returns a message indicating whether the sub-session was created successfully, which must be
    /// sent to the client.
    fn on_create_sub_session(
        &mut self,
        session_id: Arc<str>,
        session_kind: SessionKind,
        options: HashMap<String, String>,
    ) -> Vec<u8> {
        let SamSessionKind::Primary { sub_sessions } = &mut self.session_kind else {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                sub_session_id = %session_id,
                kind = ?self.session_kind,
                "sub-sessions not supported for the configured session kind",
            );

            return b"SESSION STATUS RESULT=I2P_ERROR MESSAGE=\"not a primary session\"\n".to_vec();
        };

        if let Some(session_kind) = sub_sessions.get(&session_id) {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                sub_session_id = %session_id,
                ?session_kind,
                "duplicate sub-session id",
            );

            return b"SESSION STATUS RESULT=DUPLICATE_ID\n".to_vec();
        }

        // `sub_session_tx` must exist since the session kind is `Primary`
        if let Err(error) =
            self.sub_session_tx
                .as_ref()
                .expect("to exist")
                .try_send(SubSessionCommand::Add {
                    primary_session_id: Arc::clone(&self.session_id),
                    sub_session_id: Arc::clone(&session_id),
                })
        {
            tracing::warn!(
                target: LOG_TARGET,
                session_id = %self.session_id,
                sub_session_id = %session_id,
                ?error,
                "failed register sub-session to sam server",
            );

            return b"SESSION STATUS RESULT=I2P_ERROR MESSAGE=\"internal error\"\n".to_vec();
        }

        // if session kind indicated datagrams, attempt to add listener into `DatagramManager`
        if core::matches!(
            session_kind,
            SessionKind::Datagram | SessionKind::Anonymous | SessionKind::Datagram2
        ) {
            if let Err(()) = self.datagram_manager.add_listener(options) {
                return b"SESSION STATUS RESULT=I2P_ERROR MESSAGE=\"invalid datagram configuration\"\n".to_vec();
            }
        }

        tracing::debug!(
            target: LOG_TARGET,
            session_id = %self.session_id,
            sub_session_id = %session_id,
            ?session_kind,
            "create new sub-session",
        );

        sub_sessions.insert(Arc::clone(&session_id), session_kind);

        format!("SESSION STATUS RESULT=OK ID=\"{session_id}\" MESSAGE=\"ADD {session_id}\"\n")
            .as_bytes()
            .to_vec()
    }
}

impl<R: Runtime> Future for SamSession<R> {
    type Output = Arc<str>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            let command = match &mut self.socket {
                None => break,
                Some(socket) => match socket.poll_next_unpin(cx) {
                    Poll::Pending => break,
                    Poll::Ready(None) => {
                        tracing::info!(
                            target: LOG_TARGET,
                            session_id = %self.session_id,
                            "session socket closed, destroy session",
                        );

                        self.stream_manager.shutdown();
                        self.socket = None;
                        break;
                    }
                    Poll::Ready(Some(command)) => command,
                },
            };

            match command {
                SamCommand::NamingLookup { name } => self.on_naming_lookup(name),
                SamCommand::CreateSubSession {
                    session_id,
                    session_kind,
                    options,
                } => {
                    let message =
                        self.on_create_sub_session(Arc::from(session_id), session_kind, options);

                    if let Some(socket) = &mut self.socket {
                        socket.send_message(message);

                        if let Some(waker) = self.waker.take() {
                            waker.wake_by_ref();
                        }
                    }
                }
                SamCommand::Quit => {
                    tracing::info!(
                        target: LOG_TARGET,
                        session_id = %self.session_id,
                        "shutting down session",
                    );
                    return Poll::Ready(Arc::clone(&self.session_id));
                }
                command => tracing::warn!(
                    target: LOG_TARGET,
                    %command,
                    "ignoring command for active session",
                ),
            }
        }

        loop {
            match self.receiver.poll_recv(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(Arc::clone(&self.session_id)),
                Poll::Ready(Some(SamSessionCommand::Connect {
                    socket,
                    destination_id,
                    options,
                    session_id,
                })) => self.on_stream_connect(socket, destination_id, options, session_id),
                Poll::Ready(Some(SamSessionCommand::Accept {
                    socket,
                    options,
                    session_id,
                })) => self.on_stream_accept(socket, options, session_id),
                Poll::Ready(Some(SamSessionCommand::Forward {
                    socket,
                    port,
                    options,
                    session_id,
                })) => self.on_stream_forward(socket, port, options, session_id),
                Poll::Ready(Some(SamSessionCommand::SendDatagram {
                    destination,
                    datagram,
                    session_id,
                    options,
                })) => self.on_send_datagram(*destination, datagram, session_id, options),
                Poll::Ready(Some(SamSessionCommand::Dummy)) => unreachable!(),
            }
        }

        loop {
            match self.stream_manager.poll_next_unpin(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(Arc::clone(&self.session_id)),
                Poll::Ready(Some(StreamManagerEvent::SendPacket {
                    delivery_style,
                    dst_port,
                    packet,
                    src_port,
                })) => {
                    let Some(message) = I2cpPayloadBuilder::<R>::new(&packet)
                        .with_protocol(Protocol::Streaming)
                        .with_source_port(src_port)
                        .with_destination_port(dst_port)
                        .build()
                    else {
                        tracing::warn!(
                            target: LOG_TARGET,
                            session_id = ?self.session_id,
                            "failed to create i2cp payload",
                        );
                        continue;
                    };

                    if let Err(error) = self.destination.send_message(delivery_style, message) {
                        tracing::warn!(
                            target: LOG_TARGET,
                            session_id = ?self.session_id,
                            ?error,
                            "failed to encrypt message",
                        );
                        debug_assert!(false);
                    };
                }
                Poll::Ready(Some(StreamManagerEvent::StreamOpened {
                    destination_id,
                    direction,
                })) => match direction {
                    Direction::Inbound => {}
                    Direction::Outbound => {
                        self.pending_outbound.remove(&destination_id);
                    }
                },
                Poll::Ready(Some(StreamManagerEvent::StreamRejected { destination_id })) => {
                    self.pending_outbound.remove(&destination_id);
                }
                Poll::Ready(Some(StreamManagerEvent::StreamClosed { destination_id })) => {
                    tracing::debug!(
                        target: LOG_TARGET,
                        session_id = ?self.session_id,
                        ?destination_id,
                        "stream closed",
                    );
                }
                Poll::Ready(Some(StreamManagerEvent::ShutDown)) => {
                    tracing::info!(
                        target: LOG_TARGET,
                        session_id = ?self.session_id,
                        "stream manager shut down, shutting down tunnel pool",
                    );
                    self.destination.shutdown();
                }
            }
        }

        loop {
            match self.destination.poll_next_unpin(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(Arc::clone(&self.session_id)),
                Poll::Ready(Some(DestinationEvent::Messages { messages })) =>
                    self.on_inbound_message(messages),
                Poll::Ready(Some(DestinationEvent::LeaseSetFound { destination_id })) =>
                    self.on_lease_set_found(destination_id),
                Poll::Ready(Some(DestinationEvent::LeaseSetNotFound {
                    destination_id,
                    error,
                })) => self.on_lease_set_not_found(destination_id, error),
                Poll::Ready(Some(DestinationEvent::TunnelPoolShutDown)) => {
                    tracing::info!(
                        target: LOG_TARGET,
                        session_id = ?self.session_id,
                        "tunnel pool shut down, shutting down session",
                    );

                    return Poll::Ready(Arc::clone(&self.session_id));
                }
                Poll::Ready(Some(DestinationEvent::CreateLeaseSet { leases })) => {
                    tracing::trace!(
                        target: LOG_TARGET,
                        session_id = ?self.session_id,
                        num_leases = ?leases.len(),
                        "create new lease set",
                    );

                    let lease_set = Bytes::from(
                        LeaseSet2 {
                            header: LeaseSet2Header {
                                destination: self.dest.clone(),
                                is_unpublished: self
                                    .options
                                    .get("i2cp.dontPublishLeaseSet")
                                    .map(|value| value.parse::<bool>().unwrap_or(false))
                                    .unwrap_or(false),
                                expires: Duration::from_secs(10 * 60).as_secs() as u32,
                                offline_signature: None,
                                published: R::time_since_epoch().as_secs() as u32,
                            },
                            public_keys: self.public_key_context.public_keys(),
                            leases,
                        }
                        .serialize(&self.signing_key),
                    );
                    self.destination.publish_lease_set(lease_set);
                }
                Poll::Ready(Some(DestinationEvent::SessionTerminated { destination_id })) => {
                    tracing::info!(
                        target: LOG_TARGET,
                        session_id = ?self.session_id,
                        destination_id = %destination_id,
                        "session termianted with remote",
                    );
                    self.stream_manager.remove_session(&destination_id);
                }
            }
        }

        loop {
            match self.lookup_futures.poll_next_unpin(cx) {
                Poll::Pending => break,
                Poll::Ready(None) => return Poll::Ready(Arc::clone(&self.session_id)),
                Poll::Ready(Some((name, result))) => {
                    let message = match result {
                        Some(destination) => {
                            tracing::trace!(
                                target: LOG_TARGET,
                                session_id = ?self.session_id,
                                %name,
                                "naming lookup succeeded",
                            );

                            format!("NAMING REPLY RESULT=OK NAME={name} VALUE={destination}\n")
                                .as_bytes()
                                .to_vec()
                        }
                        None => {
                            tracing::warn!(
                                target: LOG_TARGET,
                                session_id = ?self.session_id,
                                %name,
                                "naming lookup failed",
                            );

                            format!("NAMING REPLY RESULT=KEY_NOT_FOUND NAME={name}\n")
                                .as_bytes()
                                .to_vec()
                        }
                    };

                    if let Some(socket) = &mut self.socket {
                        socket.send_message(message);

                        if let Some(waker) = self.waker.take() {
                            waker.wake_by_ref();
                        }
                    }
                }
            }
        }

        self.waker = Some(cx.waker().clone());
        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        crypto::SigningPrivateKey,
        events::{EventManager, EventSubscriber},
        netdb::{NetDbAction, NetDbActionRecycle, NetDbHandle},
        primitives::Destination,
        profile::ProfileStorage,
        runtime::{
            mock::{MockRuntime, MockTcpStream},
            TcpStream,
        },
        sam::{parser::SessionKind, socket::SamSocket},
        tunnel::{TunnelMessage, TunnelMessageRecycle, TunnelPoolEvent, TunnelPoolHandle},
    };
    use thingbuf::mpsc;
    use tokio::{
        io::{AsyncBufReadExt, AsyncReadExt, BufReader},
        net,
    };

    #[allow(unused)]
    struct TestSessionContext {
        client_socket: net::TcpStream,
        datagram_rx: Receiver<(u16, Vec<u8>)>,
        event_manager: EventManager<MockRuntime>,
        event_subscriber: EventSubscriber,
        netdb_rx: mpsc::Receiver<NetDbAction, NetDbActionRecycle>,
        shutdown_rx: futures_channel::oneshot::Receiver<()>,
        sub_rx: Receiver<SubSessionCommand>,
        tm_recv: mpsc::Receiver<TunnelMessage, TunnelMessageRecycle>,
        tp_event: mpsc::Sender<TunnelPoolEvent>,
        tx: Sender<SamSessionCommand<MockRuntime>, SamSessionCommandRecycle>,
    }

    async fn create_session() -> (SamSession<MockRuntime>, TestSessionContext) {
        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();

        let signing_key = SigningPrivateKey::random(MockRuntime::rng());
        let destination = Destination::new::<MockRuntime>(signing_key.public());

        let (datagram_tx, datagram_rx) = mpsc::channel(10);
        let (sub_tx, sub_rx) = mpsc::channel(10);
        let (netdb_handle, netdb_rx) = NetDbHandle::create();
        let (event_manager, event_subscriber, event_handle) =
            EventManager::new(None, MockRuntime::register_metrics(vec![], None));
        let (tunnel_pool_handle, tm_recv, tp_event, shutdown_rx) = TunnelPoolHandle::create();
        let (tx, rx) = mpsc::with_recycle(64, SamSessionCommandRecycle::default());

        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());

        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (client_socket, _) = stream2.unwrap();
        let options =
            HashMap::from_iter([(String::from("i2cp.leaseSetEncType"), String::from("6,4"))]);

        (
            SamSession::new(SamSessionContext {
                address_book: None,
                datagram_tx,
                destination: DestinationContext {
                    destination,
                    private_key: Vec::new(),
                    signing_key: Box::new(signing_key),
                },
                event_handle,
                inbound: Default::default(),
                netdb_handle,
                options,
                outbound: Default::default(),
                profile_storage: ProfileStorage::new(&[], &[]),
                receiver: rx,
                session_id: "test".into(),
                session_kind: SessionKind::Stream,
                socket,
                sub_session_tx: Some(sub_tx),
                tunnel_pool_handle,
            }),
            TestSessionContext {
                client_socket,
                datagram_rx,
                event_manager,
                event_subscriber,
                netdb_rx,
                shutdown_rx,
                sub_rx,
                tm_recv,
                tp_event,
                tx,
            },
        )
    }

    #[tokio::test]
    async fn create_stream_sub_session() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Primary {
            sub_sessions: HashMap::new(),
        };

        let result =
            session.on_create_sub_session("sub1".into(), SessionKind::Stream, HashMap::new());
        assert!(String::from_utf8_lossy(&result).contains("RESULT=OK"));

        if let SamSessionKind::Primary { sub_sessions } = &session.session_kind {
            assert!(sub_sessions.contains_key("sub1"));
            assert_eq!(sub_sessions.get("sub1"), Some(&SessionKind::Stream));
        }
    }

    #[tokio::test]
    async fn duplicate_sub_session() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Primary {
            sub_sessions: HashMap::new(),
        };

        // Create first sub-session
        let _ = session.on_create_sub_session("sub1".into(), SessionKind::Stream, HashMap::new());

        // Try to create duplicate
        let result =
            session.on_create_sub_session("sub1".into(), SessionKind::Stream, HashMap::new());
        assert!(String::from_utf8_lossy(&result).contains("DUPLICATE_ID"));
    }

    #[tokio::test]
    async fn non_primary_sub_session() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Stream;

        let result =
            session.on_create_sub_session("sub1".into(), SessionKind::Stream, HashMap::new());
        assert!(String::from_utf8_lossy(&result).contains("not a primary session"));
    }

    #[tokio::test]
    async fn create_datagram_sub_session() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Primary {
            sub_sessions: HashMap::new(),
        };

        let mut options = HashMap::new();
        options.insert("HOST".to_string(), "127.0.0.1".to_string());
        options.insert("PORT".to_string(), "1234".to_string());

        let result = session.on_create_sub_session("sub1".into(), SessionKind::Datagram, options);
        assert!(String::from_utf8_lossy(&result).contains("RESULT=OK"));

        if let SamSessionKind::Primary { sub_sessions } = &session.session_kind {
            assert!(sub_sessions.contains_key("sub1"));
            assert_eq!(sub_sessions.get("sub1"), Some(&SessionKind::Datagram));
        }
    }

    #[tokio::test]
    async fn create_multiple_datagram_sub_sessions() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Primary {
            sub_sessions: HashMap::new(),
        };

        // First subsession with default FROM_PORT (0)
        let mut options1 = HashMap::new();
        options1.insert("HOST".to_string(), "127.0.0.1".to_string());
        options1.insert("PORT".to_string(), "1234".to_string());

        let result = session.on_create_sub_session("sub1".into(), SessionKind::Datagram, options1);
        assert!(String::from_utf8_lossy(&result).contains("RESULT=OK"));

        // Second subsession with explicit FROM_PORT
        let mut options2 = HashMap::new();
        options2.insert("HOST".to_string(), "127.0.0.1".to_string());
        options2.insert("PORT".to_string(), "5678".to_string());
        options2.insert("FROM_PORT".to_string(), "9999".to_string());

        let result = session.on_create_sub_session("sub2".into(), SessionKind::Datagram, options2);
        assert!(String::from_utf8_lossy(&result).contains("RESULT=OK"));

        // Third subsession with different FROM_PORT
        let mut options3 = HashMap::new();
        options3.insert("HOST".to_string(), "127.0.0.1".to_string());
        options3.insert("PORT".to_string(), "8080".to_string());
        options3.insert("FROM_PORT".to_string(), "7777".to_string());

        let result = session.on_create_sub_session("sub3".into(), SessionKind::Datagram, options3);
        assert!(String::from_utf8_lossy(&result).contains("RESULT=OK"));

        // Verify all subsessions were registered
        if let SamSessionKind::Primary { sub_sessions } = &session.session_kind {
            assert_eq!(sub_sessions.len(), 3);
            assert_eq!(sub_sessions.get("sub1"), Some(&SessionKind::Datagram));
            assert_eq!(sub_sessions.get("sub2"), Some(&SessionKind::Datagram));
            assert_eq!(sub_sessions.get("sub3"), Some(&SessionKind::Datagram));
        }

        // Try to create subsession with duplicate FROM_PORT (should fail)
        let mut options4 = HashMap::new();
        options4.insert("HOST".to_string(), "127.0.0.1".to_string());
        options4.insert("PORT".to_string(), "4444".to_string());
        options4.insert("FROM_PORT".to_string(), "9999".to_string());

        let result = session.on_create_sub_session("sub4".into(), SessionKind::Datagram, options4);
        assert!(String::from_utf8_lossy(&result).contains("invalid datagram configuration"));

        // Verify the failed attempt didn't affect existing mappings
        if let SamSessionKind::Primary { sub_sessions } = &session.session_kind {
            assert_eq!(sub_sessions.len(), 3);
        }
    }

    #[tokio::test]
    async fn reject_datagram_sub_session_with_occupied_port() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Primary {
            sub_sessions: HashMap::new(),
        };

        // Create first subsession with PORT 1234
        let mut options1 = HashMap::new();
        options1.insert("HOST".to_string(), "127.0.0.1".to_string());
        options1.insert("PORT".to_string(), "1234".to_string());
        options1.insert("FROM_PORT".to_string(), "5555".to_string());

        let result = session.on_create_sub_session("sub1".into(), SessionKind::Datagram, options1);
        assert!(String::from_utf8_lossy(&result).contains("RESULT=OK"));

        // Try to create another subsession with same PORT but different FROM_PORT
        let mut options2 = HashMap::new();
        options2.insert("HOST".to_string(), "127.0.0.1".to_string());
        options2.insert("PORT".to_string(), "1234".to_string());
        options2.insert("FROM_PORT".to_string(), "5555".to_string());

        let result = session.on_create_sub_session("sub2".into(), SessionKind::Datagram, options2);
        assert!(String::from_utf8_lossy(&result).contains("invalid datagram configuration"));

        // Verify only the first subsession was registered
        if let SamSessionKind::Primary { sub_sessions } = &session.session_kind {
            assert_eq!(sub_sessions.len(), 1);
            assert_eq!(sub_sessions.get("sub1"), Some(&SessionKind::Datagram));
        }
    }

    #[tokio::test]
    async fn register_sub_session_sam_server_exited() {
        let (mut session, _) = create_session().await;
        session.session_kind = SamSessionKind::Primary {
            sub_sessions: HashMap::new(),
        };

        let result =
            session.on_create_sub_session("sub1".into(), SessionKind::Stream, HashMap::new());
        assert!(String::from_utf8_lossy(&result).contains("internal error"));
    }

    #[tokio::test]
    async fn naming_lookup_me() {
        let (mut session, mut ctx) = create_session().await;
        session.on_naming_lookup("ME".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify response contains base64 encoded destination
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");

        assert!(response.contains("NAMING REPLY RESULT=OK NAME=ME VALUE="));
        assert!(response.ends_with("\n"));
    }

    #[tokio::test]
    async fn naming_lookup_b32_invalid() {
        let (mut session, mut ctx) = create_session().await;
        session.on_naming_lookup("invalid.b32.i2p".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify response contains base64 encoded destination
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");
        assert!(response.contains("RESULT=INVALID_KEY"));
        assert!(response.ends_with("\n"));
    }

    #[tokio::test]
    async fn naming_lookup_b32_with_http() {
        let (mut session, mut ctx) = create_session().await;

        // test with http:// prefix
        session.on_naming_lookup("http://abcdef.b32.i2p".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify error response when no address book exists
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");
        assert!(response.contains("RESULT=INVALID_KEY"));
    }

    #[tokio::test]
    async fn naming_lookup_b32_with_https() {
        let (mut session, mut ctx) = create_session().await;

        // test with https:// prefix
        session.on_naming_lookup("https://abcdef.b32.i2p".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify error response when no address book exists
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");
        assert!(response.contains("RESULT=INVALID_KEY"));
    }

    #[tokio::test]
    async fn naming_lookup_i2p_no_addressbook() {
        let (mut session, mut ctx) = create_session().await;
        session.on_naming_lookup("example.i2p".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify error response when no address book exists
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");

        assert!(response.contains("RESULT=KEY_NOT_FOUND"));
        assert!(response.ends_with("\n"));
    }

    #[tokio::test]
    async fn naming_lookup_invalid_name() {
        let (mut session, mut ctx) = create_session().await;
        session.on_naming_lookup("invalid-name-without-tld".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify error response for invalid hostname
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");

        assert!(response.contains("RESULT=INVALID_KEY"));
        assert!(response.ends_with("\n"));
    }

    #[tokio::test]
    async fn naming_lookup_clearnet() {
        let (mut session, mut ctx) = create_session().await;
        session.on_naming_lookup("https://google.com".to_string());
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify error response for invalid hostname
        let mut reader = BufReader::new(&mut ctx.client_socket);
        let mut response = String::new();

        // discard `SESSION STATUS` message
        reader.read_line(&mut response).await.expect("to succeed");

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");

        assert!(response.contains("RESULT=INVALID_KEY"));
        assert!(response.ends_with("\n"));
    }

    #[tokio::test]
    async fn stream_connect_for_repliable() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Datagram {
            kind: SessionKind::Datagram,
        };

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_connect(
            socket,
            DestinationId::random(),
            HashMap::new(),
            Arc::from("hello"),
        );

        let mut buf = vec![0u8; 128];
        match client_socket.read(&mut buf).await {
            Err(_) | Ok(0) => {}
            _ => panic!("invalid response"),
        }
    }

    #[tokio::test]
    async fn stream_connect_for_anonymous() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Datagram {
            kind: SessionKind::Anonymous,
        };

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_connect(
            socket,
            DestinationId::random(),
            HashMap::new(),
            Arc::from("hello"),
        );

        let mut buf = vec![0u8; 128];
        match client_socket.read(&mut buf).await {
            Err(_) | Ok(0) => {}
            _ => panic!("invalid response"),
        }
    }

    #[tokio::test]
    async fn stream_connect_for_self() {
        let (mut session, _ctx) = create_session().await;

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_connect(
            socket,
            session.dest.id(),
            HashMap::new(),
            Arc::from("hello"),
        );
        tokio::spawn(async move { session.socket.as_mut().expect("to exist").next().await });

        // verify error response for invalid hostname
        let mut reader = BufReader::new(&mut client_socket);
        let mut response = String::new();

        // read `NAMING LOOKUP` message
        reader.read_line(&mut response).await.expect("to succeed");

        assert!(response.contains("STREAM STATUS RESULT=CANT_REACH_PEER"));
    }

    #[tokio::test]
    async fn stream_accept_for_repliable() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Datagram {
            kind: SessionKind::Datagram,
        };

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_accept(socket, HashMap::new(), Arc::from("hello"));

        let mut buf = vec![0u8; 128];
        match client_socket.read(&mut buf).await {
            Err(_) | Ok(0) => {}
            _ => panic!("invalid response"),
        }
    }

    #[tokio::test]
    async fn stream_accept_for_anonymous() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Datagram {
            kind: SessionKind::Anonymous,
        };

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_accept(socket, HashMap::new(), Arc::from("hello"));

        let mut buf = vec![0u8; 128];
        match client_socket.read(&mut buf).await {
            Err(_) | Ok(0) => {}
            _ => panic!("invalid response"),
        }
    }

    #[tokio::test]
    async fn stream_forward_for_repliable() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Datagram {
            kind: SessionKind::Datagram,
        };

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_forward(socket, 8888, HashMap::new(), Arc::from("hello"));

        let mut buf = vec![0u8; 128];
        match client_socket.read(&mut buf).await {
            Err(_) | Ok(0) => {}
            _ => panic!("invalid response"),
        }
    }

    #[tokio::test]
    async fn stream_forward_for_anonymous() {
        let (mut session, _ctx) = create_session().await;
        session.session_kind = SamSessionKind::Datagram {
            kind: SessionKind::Anonymous,
        };

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_forward(socket, 8888, HashMap::new(), Arc::from("hello"));

        let mut buf = vec![0u8; 128];
        match client_socket.read(&mut buf).await {
            Err(_) | Ok(0) => {}
            _ => panic!("invalid response"),
        }
    }

    #[tokio::test]
    async fn stream_accept_then_forward() {
        let (mut session, _ctx) = create_session().await;

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_accept(socket, HashMap::new(), Arc::from("hello"));

        // read `STREAM ACCEPT` response
        let future = async {
            let mut reader = BufReader::new(&mut client_socket);
            let mut response = String::new();
            reader.read_line(&mut response).await.expect("to succeed");
            assert!(response.contains("STREAM STATUS RESULT=OK"));
        };
        assert!(tokio::time::timeout(Duration::from_secs(1), future).await.is_ok());

        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_forward(socket, 8888, HashMap::new(), Arc::from("hello"));

        // read `STREAM FORWARD` response
        let future = async {
            let mut reader = BufReader::new(&mut client_socket);
            let mut response = String::new();
            reader.read_line(&mut response).await.expect("to succeed");
            assert!(response.contains("STREAM STATUS RESULT=I2P_ERROR"));
        };
        assert!(tokio::time::timeout(Duration::from_secs(1), future).await.is_ok());
    }

    #[tokio::test]
    async fn stream_forward_then_accept() {
        let (mut session, _ctx) = create_session().await;

        let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_forward(socket, address.port(), HashMap::new(), Arc::from("hello"));

        // read `STREAM FORWARD` response
        let future = async {
            let mut reader = BufReader::new(&mut client_socket);
            let mut response = String::new();
            reader.read_line(&mut response).await.expect("to succeed");
            assert!(response.contains("STREAM STATUS RESULT=OK"));
        };
        assert!(tokio::time::timeout(Duration::from_secs(1), future).await.is_ok());

        let (stream1, stream2) = tokio::join!(MockTcpStream::connect(address), listener.accept());
        let socket = Box::new(SamSocket::<MockRuntime>::new(stream1.unwrap()));
        let (mut client_socket, _) = stream2.unwrap();

        session.on_stream_accept(socket, HashMap::new(), Arc::from("hello"));

        // read `STREAM ACCEPT` response
        let future = async {
            let mut reader = BufReader::new(&mut client_socket);
            let mut response = String::new();
            reader.read_line(&mut response).await.expect("to succeed");
            assert!(response.contains("STREAM STATUS RESULT=I2P_ERROR"));
        };
        assert!(tokio::time::timeout(Duration::from_secs(1), future).await.is_ok());
    }
}