netstack3_icmp_echo/
socket.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
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! ICMP Echo Sockets.

use alloc::vec::Vec;
use core::borrow::Borrow;
use core::convert::Infallible as Never;
use core::fmt::Debug;
use core::marker::PhantomData;
use core::num::{NonZeroU16, NonZeroU8};
use core::ops::ControlFlow;
use lock_order::lock::{DelegatedOrderedLockAccess, OrderedLockAccess, OrderedLockRef};

use derivative::Derivative;
use either::Either;
use log::{debug, trace};
use net_types::ip::{GenericOverIp, Ip, IpVersionMarker};
use net_types::{SpecifiedAddr, ZonedAddr};
use netstack3_base::socket::{
    self, AddrIsMappedError, AddrVec, AddrVecIter, ConnAddr, ConnInfoAddr, ConnIpAddr,
    IncompatibleError, InsertError, ListenerAddrInfo, MaybeDualStack, ShutdownType, SocketIpAddr,
    SocketMapAddrSpec, SocketMapAddrStateSpec, SocketMapConflictPolicy, SocketMapStateSpec,
};
use netstack3_base::socketmap::{IterShadows as _, SocketMap};
use netstack3_base::sync::{RwLock, StrongRc};
use netstack3_base::{
    AnyDevice, ContextPair, CounterContext, DeviceIdContext, IcmpIpExt, Inspector,
    InspectorDeviceExt, LocalAddressError, PortAllocImpl, ReferenceNotifiers,
    RemoveResourceResultWithContext, RngContext, SocketError, StrongDeviceIdentifier,
    UninstantiableWrapper, WeakDeviceIdentifier,
};
use netstack3_datagram::{
    self as datagram, DatagramApi, DatagramFlowId, DatagramSocketMapSpec, DatagramSocketSet,
    DatagramSocketSpec, DatagramSpecBoundStateContext, DatagramSpecStateContext,
    DatagramStateContext, ExpectedUnboundError, NonDualStackConverter,
    NonDualStackDatagramSpecBoundStateContext,
};
use netstack3_ip::icmp::{EchoTransportContextMarker, IcmpRxCounters};
use netstack3_ip::socket::SocketHopLimits;
use netstack3_ip::{
    IpTransportContext, Mark, MarkDomain, MulticastMembershipHandler, ReceiveIpPacketMeta,
    TransportIpContext, TransportReceiveError,
};
use packet::{BufferMut, ParsablePacket as _, ParseBuffer as _, Serializer};
use packet_formats::icmp::{IcmpEchoReply, IcmpEchoRequest, IcmpPacketBuilder, IcmpPacketRaw};
use packet_formats::ip::{IpProtoExt, Ipv4Proto, Ipv6Proto};

/// A marker trait for all IP extensions required by ICMP sockets.
pub trait IpExt: datagram::IpExt + IcmpIpExt {}
impl<O: datagram::IpExt + IcmpIpExt> IpExt for O {}

/// Holds the stack's ICMP echo sockets.
#[derive(Derivative, GenericOverIp)]
#[derivative(Default(bound = ""))]
#[generic_over_ip(I, Ip)]
pub struct IcmpSockets<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> {
    bound_and_id_allocator: RwLock<BoundSockets<I, D, BT>>,
    // Destroy all_sockets last so the strong references in the demux are
    // dropped before the primary references in the set.
    all_sockets: RwLock<IcmpSocketSet<I, D, BT>>,
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    OrderedLockAccess<BoundSockets<I, D, BT>> for IcmpSockets<I, D, BT>
{
    type Lock = RwLock<BoundSockets<I, D, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.bound_and_id_allocator)
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    OrderedLockAccess<IcmpSocketSet<I, D, BT>> for IcmpSockets<I, D, BT>
{
    type Lock = RwLock<IcmpSocketSet<I, D, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.all_sockets)
    }
}

/// An ICMP socket.
#[derive(GenericOverIp, Derivative)]
#[derivative(Eq(bound = ""), PartialEq(bound = ""), Hash(bound = ""))]
#[generic_over_ip(I, Ip)]

pub struct IcmpSocketId<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>(
    datagram::StrongRc<I, D, Icmp<BT>>,
);

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> Clone
    for IcmpSocketId<I, D, BT>
{
    #[cfg_attr(feature = "instrumented", track_caller)]
    fn clone(&self) -> Self {
        let Self(rc) = self;
        Self(StrongRc::clone(rc))
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    From<datagram::StrongRc<I, D, Icmp<BT>>> for IcmpSocketId<I, D, BT>
{
    fn from(value: datagram::StrongRc<I, D, Icmp<BT>>) -> Self {
        Self(value)
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    Borrow<datagram::StrongRc<I, D, Icmp<BT>>> for IcmpSocketId<I, D, BT>
{
    fn borrow(&self) -> &datagram::StrongRc<I, D, Icmp<BT>> {
        let Self(rc) = self;
        rc
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    PartialEq<WeakIcmpSocketId<I, D, BT>> for IcmpSocketId<I, D, BT>
{
    fn eq(&self, other: &WeakIcmpSocketId<I, D, BT>) -> bool {
        let Self(rc) = self;
        let WeakIcmpSocketId(weak) = other;
        StrongRc::weak_ptr_eq(rc, weak)
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> Debug
    for IcmpSocketId<I, D, BT>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self(rc) = self;
        f.debug_tuple("IcmpSocketId").field(&StrongRc::debug_id(rc)).finish()
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> IcmpSocketId<I, D, BT> {
    /// Returns the inner state for this socket, to be used in conjunction with
    /// lock ordering mechanisms.
    #[cfg(any(test, feature = "testutils"))]
    pub fn state(&self) -> &RwLock<IcmpSocketState<I, D, BT>> {
        let Self(rc) = self;
        rc.state()
    }

    /// Returns a means to debug outstanding references to this socket.
    pub fn debug_references(&self) -> impl Debug {
        let Self(rc) = self;
        StrongRc::debug_references(rc)
    }

    /// Downgrades this ID to a weak reference.
    pub fn downgrade(&self) -> WeakIcmpSocketId<I, D, BT> {
        let Self(rc) = self;
        WeakIcmpSocketId(StrongRc::downgrade(rc))
    }

    /// Returns external data associated with this socket.
    pub fn external_data(&self) -> &BT::ExternalData<I> {
        let Self(rc) = self;
        rc.external_data()
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    DelegatedOrderedLockAccess<IcmpSocketState<I, D, BT>> for IcmpSocketId<I, D, BT>
{
    type Inner = datagram::ReferenceState<I, D, Icmp<BT>>;
    fn delegate_ordered_lock_access(&self) -> &Self::Inner {
        let Self(rc) = self;
        &*rc
    }
}

/// A weak reference to an ICMP socket.
#[derive(GenericOverIp, Derivative)]
#[derivative(Eq(bound = ""), PartialEq(bound = ""), Hash(bound = ""), Clone(bound = ""))]
#[generic_over_ip(I, Ip)]
pub struct WeakIcmpSocketId<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>(
    datagram::WeakRc<I, D, Icmp<BT>>,
);

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> PartialEq<IcmpSocketId<I, D, BT>>
    for WeakIcmpSocketId<I, D, BT>
{
    fn eq(&self, other: &IcmpSocketId<I, D, BT>) -> bool {
        PartialEq::eq(other, self)
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> Debug
    for WeakIcmpSocketId<I, D, BT>
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self(rc) = self;
        f.debug_tuple("WeakIcmpSocketId").field(&rc.debug_id()).finish()
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> WeakIcmpSocketId<I, D, BT> {
    #[cfg_attr(feature = "instrumented", track_caller)]
    pub fn upgrade(&self) -> Option<IcmpSocketId<I, D, BT>> {
        let Self(rc) = self;
        rc.upgrade().map(IcmpSocketId)
    }
}

/// The set of ICMP sockets.
pub type IcmpSocketSet<I, D, BT> = DatagramSocketSet<I, D, Icmp<BT>>;
/// The state of an ICMP socket.
pub type IcmpSocketState<I, D, BT> = datagram::SocketState<I, D, Icmp<BT>>;

/// The context required by the ICMP layer in order to deliver events related to
/// ICMP sockets.
pub trait IcmpEchoBindingsContext<I: IpExt, D: StrongDeviceIdentifier>:
    IcmpEchoBindingsTypes + ReferenceNotifiers + RngContext
{
    /// Receives an ICMP echo reply.
    fn receive_icmp_echo_reply<B: BufferMut>(
        &mut self,
        conn: &IcmpSocketId<I, D::Weak, Self>,
        device_id: &D,
        src_ip: I::Addr,
        dst_ip: I::Addr,
        id: u16,
        data: B,
    );
}

/// The bindings context providing external types to ICMP sockets.
///
/// # Discussion
///
/// We'd like this trait to take an `I` type parameter instead of using GAT to
/// get the IP version, however we end up with problems due to the shape of
/// [`DatagramSocketSpec`] and the underlying support for dual stack sockets.
///
/// This is completely fine for all known implementations, except for a rough
/// edge in fake tests bindings contexts that are already parameterized on I
/// themselves. This is still better than relying on `Box<dyn Any>` to keep the
/// external data in our references so we take the rough edge.
pub trait IcmpEchoBindingsTypes: Sized + 'static {
    /// Opaque bindings data held by core for a given IP version.
    type ExternalData<I: Ip>: Debug + Send + Sync + 'static;
}

/// Resolve coherence issues by requiring a trait implementation with no type
/// parameters, which makes the blanket implementations for the datagram specs
/// viable.
pub trait IcmpEchoContextMarker {}

/// A Context that provides access to the sockets' states.
pub trait IcmpEchoBoundStateContext<I: IcmpIpExt + IpExt, BC: IcmpEchoBindingsTypes>:
    DeviceIdContext<AnyDevice> + IcmpEchoContextMarker
{
    /// The inner context providing IP socket access.
    type IpSocketsCtx<'a>: TransportIpContext<I, BC>
        + MulticastMembershipHandler<I, BC>
        + DeviceIdContext<AnyDevice, DeviceId = Self::DeviceId, WeakDeviceId = Self::WeakDeviceId>
        + CounterContext<IcmpRxCounters<I>>;

    /// Calls the function with a mutable reference to `IpSocketsCtx` and
    /// a mutable reference to ICMP sockets.
    fn with_icmp_ctx_and_sockets_mut<
        O,
        F: FnOnce(&mut Self::IpSocketsCtx<'_>, &mut BoundSockets<I, Self::WeakDeviceId, BC>) -> O,
    >(
        &mut self,
        cb: F,
    ) -> O;
}

/// A Context that provides access to the sockets' states.
pub trait IcmpEchoStateContext<I: IcmpIpExt + IpExt, BC: IcmpEchoBindingsTypes>:
    DeviceIdContext<AnyDevice> + IcmpEchoContextMarker
{
    /// The inner socket context.
    type SocketStateCtx<'a>: IcmpEchoBoundStateContext<I, BC>
        + DeviceIdContext<AnyDevice, DeviceId = Self::DeviceId, WeakDeviceId = Self::WeakDeviceId>;

    /// Calls the function with mutable access to the set with all ICMP
    /// sockets.
    fn with_all_sockets_mut<O, F: FnOnce(&mut IcmpSocketSet<I, Self::WeakDeviceId, BC>) -> O>(
        &mut self,
        cb: F,
    ) -> O;

    /// Calls the function with immutable access to the set with all ICMP
    /// sockets.
    fn with_all_sockets<O, F: FnOnce(&IcmpSocketSet<I, Self::WeakDeviceId, BC>) -> O>(
        &mut self,
        cb: F,
    ) -> O;

    /// Calls the function without access to ICMP socket state.
    fn with_bound_state_context<O, F: FnOnce(&mut Self::SocketStateCtx<'_>) -> O>(
        &mut self,
        cb: F,
    ) -> O;

    /// Calls the function with an immutable reference to the given socket's
    /// state.
    fn with_socket_state<
        O,
        F: FnOnce(&mut Self::SocketStateCtx<'_>, &IcmpSocketState<I, Self::WeakDeviceId, BC>) -> O,
    >(
        &mut self,
        id: &IcmpSocketId<I, Self::WeakDeviceId, BC>,
        cb: F,
    ) -> O;

    /// Calls the function with a mutable reference to the given socket's state.
    fn with_socket_state_mut<
        O,
        F: FnOnce(&mut Self::SocketStateCtx<'_>, &mut IcmpSocketState<I, Self::WeakDeviceId, BC>) -> O,
    >(
        &mut self,
        id: &IcmpSocketId<I, Self::WeakDeviceId, BC>,
        cb: F,
    ) -> O;

    /// Call `f` with each socket's state.
    fn for_each_socket<
        F: FnMut(
            &mut Self::SocketStateCtx<'_>,
            &IcmpSocketId<I, Self::WeakDeviceId, BC>,
            &IcmpSocketState<I, Self::WeakDeviceId, BC>,
        ),
    >(
        &mut self,
        cb: F,
    );
}

/// Uninstantiatable type for implementing [`DatagramSocketSpec`].
pub struct Icmp<BT>(PhantomData<BT>, Never);

impl<BT: IcmpEchoBindingsTypes> DatagramSocketSpec for Icmp<BT> {
    const NAME: &'static str = "ICMP_ECHO";
    type AddrSpec = IcmpAddrSpec;

    type SocketId<I: datagram::IpExt, D: WeakDeviceIdentifier> = IcmpSocketId<I, D, BT>;

    type OtherStackIpOptions<I: datagram::IpExt, D: WeakDeviceIdentifier> = ();

    type SharingState = ();

    type SocketMapSpec<I: datagram::IpExt + datagram::DualStackIpExt, D: WeakDeviceIdentifier> =
        IcmpSocketMapStateSpec<I, D, BT>;

    fn ip_proto<I: IpProtoExt>() -> I::Proto {
        I::map_ip((), |()| Ipv4Proto::Icmp, |()| Ipv6Proto::Icmpv6)
    }

    fn make_bound_socket_map_id<I: datagram::IpExt, D: WeakDeviceIdentifier>(
        s: &Self::SocketId<I, D>,
    ) -> <Self::SocketMapSpec<I, D> as datagram::DatagramSocketMapSpec<
        I,
        D,
        Self::AddrSpec,
    >>::BoundSocketId{
        s.clone()
    }

    type Serializer<I: datagram::IpExt, B: BufferMut> =
        packet::Nested<B, IcmpPacketBuilder<I, IcmpEchoRequest>>;
    type SerializeError = packet_formats::error::ParseError;

    type ExternalData<I: Ip> = BT::ExternalData<I>;

    fn make_packet<I: datagram::IpExt, B: BufferMut>(
        mut body: B,
        addr: &socket::ConnIpAddr<
            I::Addr,
            <Self::AddrSpec as SocketMapAddrSpec>::LocalIdentifier,
            <Self::AddrSpec as SocketMapAddrSpec>::RemoteIdentifier,
        >,
    ) -> Result<Self::Serializer<I, B>, Self::SerializeError> {
        let ConnIpAddr { local: (local_ip, id), remote: (remote_ip, ()) } = addr;
        let icmp_echo: packet_formats::icmp::IcmpPacketRaw<I, &[u8], IcmpEchoRequest> =
            body.parse()?;
        let icmp_builder = IcmpPacketBuilder::<I, _>::new(
            local_ip.addr(),
            remote_ip.addr(),
            packet_formats::icmp::IcmpUnusedCode,
            IcmpEchoRequest::new(id.get(), icmp_echo.message().seq()),
        );
        Ok(body.encapsulate(icmp_builder))
    }

    fn try_alloc_listen_identifier<I: datagram::IpExt, D: WeakDeviceIdentifier>(
        bindings_ctx: &mut impl RngContext,
        is_available: impl Fn(
            <Self::AddrSpec as SocketMapAddrSpec>::LocalIdentifier,
        ) -> Result<(), datagram::InUseError>,
    ) -> Option<<Self::AddrSpec as SocketMapAddrSpec>::LocalIdentifier> {
        let mut port = IcmpPortAlloc::<I, D, BT>::rand_ephemeral(&mut bindings_ctx.rng());
        for _ in IcmpPortAlloc::<I, D, BT>::EPHEMERAL_RANGE {
            // We can unwrap here because we know that the EPHEMERAL_RANGE doesn't
            // include 0.
            let tryport = NonZeroU16::new(port.get()).unwrap();
            match is_available(tryport) {
                Ok(()) => return Some(tryport),
                Err(datagram::InUseError {}) => port.next(),
            }
        }
        None
    }

    type ListenerIpAddr<I: datagram::IpExt> = socket::ListenerIpAddr<I::Addr, NonZeroU16>;

    type ConnIpAddr<I: datagram::IpExt> = ConnIpAddr<
        I::Addr,
        <Self::AddrSpec as SocketMapAddrSpec>::LocalIdentifier,
        <Self::AddrSpec as SocketMapAddrSpec>::RemoteIdentifier,
    >;

    type ConnState<I: datagram::IpExt, D: WeakDeviceIdentifier> =
        datagram::ConnState<I, I, D, Self>;
    // Store the remote port/id set by `connect`. This does not participate in
    // demuxing, so not part of the socketmap, but we need to store it so that
    // it can be reported later.
    type ConnStateExtra = u16;

    fn conn_info_from_state<I: IpExt, D: WeakDeviceIdentifier>(
        state: &Self::ConnState<I, D>,
    ) -> datagram::ConnInfo<I::Addr, D> {
        let ConnAddr { ip, device } = state.addr();
        let extra = state.extra();
        let ConnInfoAddr { local: (local_ip, local_identifier), remote: (remote_ip, ()) } =
            ip.clone().into();
        datagram::ConnInfo::new(local_ip, local_identifier, remote_ip, *extra, || {
            // The invariant that a zone is present if needed is upheld by connect.
            device.clone().expect("device must be bound for addresses that require zones")
        })
    }

    fn try_alloc_local_id<I: IpExt, D: WeakDeviceIdentifier, BC: RngContext>(
        bound: &IcmpBoundSockets<I, D, BT>,
        bindings_ctx: &mut BC,
        flow: datagram::DatagramFlowId<I::Addr, ()>,
    ) -> Option<NonZeroU16> {
        let mut rng = bindings_ctx.rng();
        netstack3_base::simple_randomized_port_alloc(&mut rng, &flow, &IcmpPortAlloc(bound), &())
            .map(|p| NonZeroU16::new(p).expect("ephemeral ports should be non-zero"))
    }
}

/// Uninstantiatable type for implementing [`SocketMapAddrSpec`].
pub enum IcmpAddrSpec {}

impl SocketMapAddrSpec for IcmpAddrSpec {
    type RemoteIdentifier = ();
    type LocalIdentifier = NonZeroU16;
}

type IcmpBoundSockets<I, D, BT> =
    datagram::BoundSockets<I, D, IcmpAddrSpec, IcmpSocketMapStateSpec<I, D, BT>>;

struct IcmpPortAlloc<'a, I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>(
    &'a IcmpBoundSockets<I, D, BT>,
);

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> PortAllocImpl
    for IcmpPortAlloc<'_, I, D, BT>
{
    const EPHEMERAL_RANGE: core::ops::RangeInclusive<u16> = 1..=u16::MAX;
    type Id = DatagramFlowId<I::Addr, ()>;
    type PortAvailableArg = ();

    fn is_port_available(&self, id: &Self::Id, port: u16, (): &()) -> bool {
        let Self(socketmap) = self;
        // We can safely unwrap here, because the ports received in
        // `is_port_available` are guaranteed to be in `EPHEMERAL_RANGE`.
        let port = NonZeroU16::new(port).unwrap();
        let conn = ConnAddr {
            ip: ConnIpAddr { local: (id.local_ip, port), remote: (id.remote_ip, ()) },
            device: None,
        };

        // A port is free if there are no sockets currently using it, and if
        // there are no sockets that are shadowing it.
        AddrVec::from(conn).iter_shadows().all(|a| match &a {
            AddrVec::Listen(l) => socketmap.listeners().get_by_addr(&l).is_none(),
            AddrVec::Conn(c) => socketmap.conns().get_by_addr(&c).is_none(),
        } && socketmap.get_shadower_counts(&a) == 0)
    }
}

/// The demux state for ICMP echo sockets.
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct BoundSockets<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> {
    pub(crate) socket_map: IcmpBoundSockets<I, D, BT>,
}

impl<I, BC, CC> NonDualStackDatagramSpecBoundStateContext<I, CC, BC> for Icmp<BC>
where
    I: IpExt + datagram::DualStackIpExt,
    BC: IcmpEchoBindingsContext<I, CC::DeviceId>,
    CC: DeviceIdContext<AnyDevice> + IcmpEchoContextMarker,
{
    fn nds_converter(_core_ctx: &CC) -> impl NonDualStackConverter<I, CC::WeakDeviceId, Self> {
        ()
    }
}

impl<I, BC, CC> DatagramSpecBoundStateContext<I, CC, BC> for Icmp<BC>
where
    I: IpExt + datagram::DualStackIpExt,
    BC: IcmpEchoBindingsContext<I, CC::DeviceId>,
    CC: IcmpEchoBoundStateContext<I, BC> + IcmpEchoContextMarker,
{
    type IpSocketsCtx<'a> = CC::IpSocketsCtx<'a>;

    // ICMP sockets doesn't support dual-stack operations.
    type DualStackContext = UninstantiableWrapper<CC>;

    type NonDualStackContext = CC;

    fn with_bound_sockets<
        O,
        F: FnOnce(&mut Self::IpSocketsCtx<'_>, &IcmpBoundSockets<I, CC::WeakDeviceId, BC>) -> O,
    >(
        core_ctx: &mut CC,
        cb: F,
    ) -> O {
        IcmpEchoBoundStateContext::with_icmp_ctx_and_sockets_mut(
            core_ctx,
            |ctx, BoundSockets { socket_map }| cb(ctx, &socket_map),
        )
    }

    fn with_bound_sockets_mut<
        O,
        F: FnOnce(&mut Self::IpSocketsCtx<'_>, &mut IcmpBoundSockets<I, CC::WeakDeviceId, BC>) -> O,
    >(
        core_ctx: &mut CC,
        cb: F,
    ) -> O {
        IcmpEchoBoundStateContext::with_icmp_ctx_and_sockets_mut(
            core_ctx,
            |ctx, BoundSockets { socket_map }| cb(ctx, socket_map),
        )
    }

    fn dual_stack_context(
        core_ctx: &mut CC,
    ) -> MaybeDualStack<&mut Self::DualStackContext, &mut Self::NonDualStackContext> {
        MaybeDualStack::NotDualStack(core_ctx)
    }

    fn with_transport_context<O, F: FnOnce(&mut Self::IpSocketsCtx<'_>) -> O>(
        core_ctx: &mut CC,
        cb: F,
    ) -> O {
        IcmpEchoBoundStateContext::with_icmp_ctx_and_sockets_mut(core_ctx, |ctx, _sockets| cb(ctx))
    }
}

impl<I, BC, CC> DatagramSpecStateContext<I, CC, BC> for Icmp<BC>
where
    I: IpExt + datagram::DualStackIpExt,
    BC: IcmpEchoBindingsContext<I, CC::DeviceId>,
    CC: IcmpEchoStateContext<I, BC>,
{
    type SocketsStateCtx<'a> = CC::SocketStateCtx<'a>;

    fn with_all_sockets_mut<O, F: FnOnce(&mut IcmpSocketSet<I, CC::WeakDeviceId, BC>) -> O>(
        core_ctx: &mut CC,
        cb: F,
    ) -> O {
        IcmpEchoStateContext::with_all_sockets_mut(core_ctx, cb)
    }

    fn with_all_sockets<O, F: FnOnce(&IcmpSocketSet<I, CC::WeakDeviceId, BC>) -> O>(
        core_ctx: &mut CC,
        cb: F,
    ) -> O {
        IcmpEchoStateContext::with_all_sockets(core_ctx, cb)
    }

    fn with_socket_state<
        O,
        F: FnOnce(&mut Self::SocketsStateCtx<'_>, &IcmpSocketState<I, CC::WeakDeviceId, BC>) -> O,
    >(
        core_ctx: &mut CC,
        id: &IcmpSocketId<I, CC::WeakDeviceId, BC>,
        cb: F,
    ) -> O {
        IcmpEchoStateContext::with_socket_state(core_ctx, id, cb)
    }

    fn with_socket_state_mut<
        O,
        F: FnOnce(&mut Self::SocketsStateCtx<'_>, &mut IcmpSocketState<I, CC::WeakDeviceId, BC>) -> O,
    >(
        core_ctx: &mut CC,
        id: &IcmpSocketId<I, CC::WeakDeviceId, BC>,
        cb: F,
    ) -> O {
        IcmpEchoStateContext::with_socket_state_mut(core_ctx, id, cb)
    }

    fn for_each_socket<
        F: FnMut(
            &mut Self::SocketsStateCtx<'_>,
            &IcmpSocketId<I, CC::WeakDeviceId, BC>,
            &IcmpSocketState<I, CC::WeakDeviceId, BC>,
        ),
    >(
        core_ctx: &mut CC,
        cb: F,
    ) {
        IcmpEchoStateContext::for_each_socket(core_ctx, cb)
    }
}

/// An uninstantiable type providing a [`SocketMapStateSpec`] implementation for
/// ICMP.
pub struct IcmpSocketMapStateSpec<I, D, BT>(PhantomData<(I, D, BT)>, Never);

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> SocketMapStateSpec
    for IcmpSocketMapStateSpec<I, D, BT>
{
    type ListenerId = IcmpSocketId<I, D, BT>;
    type ConnId = IcmpSocketId<I, D, BT>;

    type AddrVecTag = ();

    type ListenerSharingState = ();
    type ConnSharingState = ();

    type ListenerAddrState = Self::ListenerId;

    type ConnAddrState = Self::ConnId;
    fn listener_tag(
        ListenerAddrInfo { has_device: _, specified_addr: _ }: ListenerAddrInfo,
        _state: &Self::ListenerAddrState,
    ) -> Self::AddrVecTag {
        ()
    }
    fn connected_tag(_has_device: bool, _state: &Self::ConnAddrState) -> Self::AddrVecTag {
        ()
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> SocketMapAddrStateSpec
    for IcmpSocketId<I, D, BT>
{
    type Id = Self;

    type SharingState = ();

    type Inserter<'a> = core::convert::Infallible
    where
        Self: 'a;

    fn new(_new_sharing_state: &Self::SharingState, id: Self::Id) -> Self {
        id
    }

    fn contains_id(&self, id: &Self::Id) -> bool {
        self == id
    }

    fn try_get_inserter<'a, 'b>(
        &'b mut self,
        _new_sharing_state: &'a Self::SharingState,
    ) -> Result<Self::Inserter<'b>, IncompatibleError> {
        Err(IncompatibleError)
    }

    fn could_insert(
        &self,
        _new_sharing_state: &Self::SharingState,
    ) -> Result<(), IncompatibleError> {
        Err(IncompatibleError)
    }

    fn remove_by_id(&mut self, _id: Self::Id) -> socket::RemoveResult {
        socket::RemoveResult::IsLast
    }
}

impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    DatagramSocketMapSpec<I, D, IcmpAddrSpec> for IcmpSocketMapStateSpec<I, D, BT>
{
    type BoundSocketId = IcmpSocketId<I, D, BT>;
}

impl<AA, I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes>
    SocketMapConflictPolicy<AA, (), I, D, IcmpAddrSpec> for IcmpSocketMapStateSpec<I, D, BT>
where
    AA: Into<AddrVec<I, D, IcmpAddrSpec>> + Clone,
{
    fn check_insert_conflicts(
        _new_sharing_state: &(),
        addr: &AA,
        socketmap: &SocketMap<AddrVec<I, D, IcmpAddrSpec>, socket::Bound<Self>>,
    ) -> Result<(), socket::InsertError> {
        let addr: AddrVec<_, _, _> = addr.clone().into();
        // Having a value present at a shadowed address is disqualifying.
        if addr.iter_shadows().any(|a| socketmap.get(&a).is_some()) {
            return Err(InsertError::ShadowAddrExists);
        }

        // Likewise, the presence of a value that shadows the target address is
        // also disqualifying.
        if socketmap.descendant_counts(&addr).len() != 0 {
            return Err(InsertError::ShadowerExists);
        }
        Ok(())
    }
}

/// The ICMP Echo sockets API.
pub struct IcmpEchoSocketApi<I: Ip, C>(C, IpVersionMarker<I>);

impl<I: Ip, C> IcmpEchoSocketApi<I, C> {
    /// Creates a new API instance.
    pub fn new(ctx: C) -> Self {
        Self(ctx, IpVersionMarker::new())
    }
}

/// A local alias for [`IcmpSocketId`] for use in [`IcmpEchoSocketApi`].
///
/// TODO(https://github.com/rust-lang/rust/issues/8995): Make this an inherent
/// associated type.
type IcmpApiSocketId<I, C> = IcmpSocketId<
    I,
    <<C as ContextPair>::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
    <C as ContextPair>::BindingsContext,
>;

impl<I, C> IcmpEchoSocketApi<I, C>
where
    I: datagram::IpExt,
    C: ContextPair,
    C::CoreContext: IcmpEchoStateContext<I, C::BindingsContext>
        // NB: This bound is somewhat redundant to StateContext but it helps the
        // compiler know we're using ICMP datagram sockets.
        + DatagramStateContext<I, C::BindingsContext, Icmp<C::BindingsContext>>,
    C::BindingsContext:
        IcmpEchoBindingsContext<I, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
{
    fn core_ctx(&mut self) -> &mut C::CoreContext {
        let Self(pair, IpVersionMarker { .. }) = self;
        pair.core_ctx()
    }

    fn datagram(&mut self) -> &mut DatagramApi<I, C, Icmp<C::BindingsContext>> {
        let Self(pair, IpVersionMarker { .. }) = self;
        DatagramApi::wrap(pair)
    }

    /// Creates a new unbound ICMP socket with default external data.
    pub fn create(&mut self) -> IcmpApiSocketId<I, C>
    where
        <C::BindingsContext as IcmpEchoBindingsTypes>::ExternalData<I>: Default,
    {
        self.create_with(Default::default())
    }

    /// Creates a new unbound ICMP socket with provided external data.
    pub fn create_with(
        &mut self,
        external_data: <C::BindingsContext as IcmpEchoBindingsTypes>::ExternalData<I>,
    ) -> IcmpApiSocketId<I, C> {
        self.datagram().create(external_data)
    }

    /// Connects an ICMP socket to remote IP.
    ///
    /// If the socket is never bound, an local ID will be allocated.
    pub fn connect(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        remote_ip: Option<
            ZonedAddr<
                SpecifiedAddr<I::Addr>,
                <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
            >,
        >,
        remote_id: u16,
    ) -> Result<(), datagram::ConnectError> {
        self.datagram().connect(id, remote_ip, (), remote_id)
    }

    /// Binds an ICMP socket to a local IP address and a local ID.
    ///
    /// Both the IP and the ID are optional. When IP is missing, the "any" IP is
    /// assumed; When the ID is missing, it will be allocated.
    pub fn bind(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        local_ip: Option<
            ZonedAddr<
                SpecifiedAddr<I::Addr>,
                <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
            >,
        >,
        icmp_id: Option<NonZeroU16>,
    ) -> Result<(), Either<ExpectedUnboundError, LocalAddressError>> {
        self.datagram().listen(id, local_ip, icmp_id)
    }

    /// Gets the information about an ICMP socket.
    pub fn get_info(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
    ) -> datagram::SocketInfo<I::Addr, <C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId>
    {
        self.datagram().get_info(id)
    }

    /// Sets the bound device for a socket.
    ///
    /// Sets the device to be used for sending and receiving packets for a
    /// socket. If the socket is not currently bound to a local address and
    /// port, the device will be used when binding.
    pub fn set_device(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        device_id: Option<&<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
    ) -> Result<(), SocketError> {
        self.datagram().set_device(id, device_id)
    }

    /// Gets the device the specified socket is bound to.
    pub fn get_bound_device(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
    ) -> Option<<C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId> {
        self.datagram().get_bound_device(id)
    }

    /// Disconnects an ICMP socket.
    pub fn disconnect(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
    ) -> Result<(), datagram::ExpectedConnError> {
        self.datagram().disconnect_connected(id)
    }

    /// Shuts down an ICMP socket.
    pub fn shutdown(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        shutdown_type: ShutdownType,
    ) -> Result<(), datagram::ExpectedConnError> {
        self.datagram().shutdown_connected(id, shutdown_type)
    }

    /// Gets the current shutdown state of an ICMP socket.
    pub fn get_shutdown(&mut self, id: &IcmpApiSocketId<I, C>) -> Option<ShutdownType> {
        self.datagram().get_shutdown_connected(id)
    }

    /// Closes an ICMP socket.
    pub fn close(
        &mut self,
        id: IcmpApiSocketId<I, C>,
    ) -> RemoveResourceResultWithContext<
        <C::BindingsContext as IcmpEchoBindingsTypes>::ExternalData<I>,
        C::BindingsContext,
    > {
        self.datagram().close(id)
    }

    /// Gets unicast IP hop limit for ICMP sockets.
    pub fn get_unicast_hop_limit(&mut self, id: &IcmpApiSocketId<I, C>) -> NonZeroU8 {
        self.datagram().get_ip_hop_limits(id).unicast
    }

    /// Gets multicast IP hop limit for ICMP sockets.
    pub fn get_multicast_hop_limit(&mut self, id: &IcmpApiSocketId<I, C>) -> NonZeroU8 {
        self.datagram().get_ip_hop_limits(id).multicast
    }

    /// Sets unicast IP hop limit for ICMP sockets.
    pub fn set_unicast_hop_limit(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        hop_limit: Option<NonZeroU8>,
    ) {
        self.datagram().update_ip_hop_limit(id, SocketHopLimits::set_unicast(hop_limit))
    }

    /// Sets multicast IP hop limit for ICMP sockets.
    pub fn set_multicast_hop_limit(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        hop_limit: Option<NonZeroU8>,
    ) {
        self.datagram().update_ip_hop_limit(id, SocketHopLimits::set_multicast(hop_limit))
    }

    /// Gets the loopback multicast option.
    pub fn get_multicast_loop(&mut self, id: &IcmpApiSocketId<I, C>) -> bool {
        self.datagram().get_multicast_loop(id)
    }

    /// Sets the loopback multicast option.
    pub fn set_multicast_loop(&mut self, id: &IcmpApiSocketId<I, C>, value: bool) {
        self.datagram().set_multicast_loop(id, value);
    }

    /// Sets the socket mark for the socket domain.
    pub fn set_mark(&mut self, id: &IcmpApiSocketId<I, C>, domain: MarkDomain, mark: Mark) {
        self.datagram().set_mark(id, domain, mark)
    }

    /// Gets the socket mark for the socket domain.
    pub fn get_mark(&mut self, id: &IcmpApiSocketId<I, C>, domain: MarkDomain) -> Mark {
        self.datagram().get_mark(id, domain)
    }

    /// Sends an ICMP packet through a connection.
    ///
    /// The socket must be connected in order for the operation to succeed.
    pub fn send<B: BufferMut>(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        body: B,
    ) -> Result<(), datagram::SendError<packet_formats::error::ParseError>> {
        self.datagram().send_conn(id, body)
    }

    /// Sends an ICMP packet with an remote address.
    ///
    /// The socket doesn't need to be connected.
    pub fn send_to<B: BufferMut>(
        &mut self,
        id: &IcmpApiSocketId<I, C>,
        remote_ip: Option<
            ZonedAddr<
                SpecifiedAddr<I::Addr>,
                <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId,
            >,
        >,
        body: B,
    ) -> Result<
        (),
        either::Either<LocalAddressError, datagram::SendToError<packet_formats::error::ParseError>>,
    > {
        self.datagram().send_to(id, remote_ip, (), body)
    }

    /// Collects all currently opened sockets, returning a cloned reference for
    /// each one.
    pub fn collect_all_sockets(&mut self) -> Vec<IcmpApiSocketId<I, C>> {
        self.datagram().collect_all_sockets()
    }

    /// Provides inspect data for ICMP echo sockets.
    pub fn inspect<N>(&mut self, inspector: &mut N)
    where
        N: Inspector
            + InspectorDeviceExt<<C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
    {
        DatagramStateContext::for_each_socket(self.core_ctx(), |_ctx, socket_id, socket_state| {
            socket_state.record_common_info(inspector, socket_id);
        });
    }
}

/// An [`IpTransportContext`] implementation for handling ICMP Echo replies.
///
/// This special implementation will panic if it receives any packets that are
/// not ICMP echo replies and any error that are not originally an ICMP Echo
/// request.
pub enum IcmpEchoIpTransportContext {}

impl EchoTransportContextMarker for IcmpEchoIpTransportContext {}

impl<
        I: IpExt,
        BC: IcmpEchoBindingsContext<I, CC::DeviceId>,
        CC: IcmpEchoBoundStateContext<I, BC>,
    > IpTransportContext<I, BC, CC> for IcmpEchoIpTransportContext
{
    fn receive_icmp_error(
        core_ctx: &mut CC,
        _bindings_ctx: &mut BC,
        _device: &CC::DeviceId,
        original_src_ip: Option<SpecifiedAddr<I::Addr>>,
        original_dst_ip: SpecifiedAddr<I::Addr>,
        mut original_body: &[u8],
        err: I::ErrorCode,
    ) {
        let echo_request = original_body
            .parse::<IcmpPacketRaw<I, _, IcmpEchoRequest>>()
            .expect("received non-echo request");

        let original_src_ip = match original_src_ip {
            Some(ip) => ip,
            None => {
                trace!("IcmpIpTransportContext::receive_icmp_error: unspecified source IP address");
                return;
            }
        };
        let original_src_ip: SocketIpAddr<_> = match original_src_ip.try_into() {
            Ok(ip) => ip,
            Err(AddrIsMappedError {}) => {
                trace!("IcmpIpTransportContext::receive_icmp_error: mapped source IP address");
                return;
            }
        };
        let original_dst_ip: SocketIpAddr<_> = match original_dst_ip.try_into() {
            Ok(ip) => ip,
            Err(AddrIsMappedError {}) => {
                trace!("IcmpIpTransportContext::receive_icmp_error: mapped destination IP address");
                return;
            }
        };

        let id = echo_request.message().id();

        core_ctx.with_icmp_ctx_and_sockets_mut(|core_ctx, sockets| {
            if let Some(conn) = sockets.socket_map.conns().get_by_addr(&ConnAddr {
                ip: ConnIpAddr {
                    local: (original_src_ip, NonZeroU16::new(id).unwrap()),
                    remote: (original_dst_ip, ()),
                },
                device: None,
            }) {
                // NB: At the moment bindings has no need to consume ICMP
                // errors, so we swallow them here.
                debug!(
                    "ICMP received ICMP error {:?} from {:?}, to {:?} on socket {:?}",
                    err, original_dst_ip, original_src_ip, conn
                );
                core_ctx
                    .increment(|counters: &IcmpRxCounters<I>| &counters.error_delivered_to_socket)
            } else {
                trace!(
                    "IcmpIpTransportContext::receive_icmp_error: Got ICMP error message for \
                    nonexistent ICMP echo socket; either the socket responsible has since been \
                    removed, or the error message was sent in error or corrupted"
                );
            }
        })
    }

    fn receive_ip_packet<B: BufferMut>(
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        device: &CC::DeviceId,
        src_ip: I::RecvSrcAddr,
        dst_ip: SpecifiedAddr<I::Addr>,
        mut buffer: B,
        meta: ReceiveIpPacketMeta<I>,
    ) -> Result<(), (B, TransportReceiveError)> {
        if let Some(delivery) = meta.transparent_override {
            unreachable!(
                "cannot perform transparent local delivery {delivery:?} to an ICMP socket; \
                transparent proxy rules can only be configured for TCP and UDP packets"
            );
        }
        // NB: We're doing raw parsing here just to extract the ID and body to
        // send up to bindings. The IP layer has performed full validation
        // including checksum for us.
        let echo_reply =
            buffer.parse::<IcmpPacketRaw<I, _, IcmpEchoReply>>().expect("received non-echo reply");
        // We never generate requests with ID zero due to local socket map.
        let Some(id) = NonZeroU16::new(echo_reply.message().id()) else { return Ok(()) };

        // Undo parse so we give out the full ICMP header.
        let meta = echo_reply.parse_metadata();
        buffer.undo_parse(meta);

        let src_ip = match SpecifiedAddr::new(src_ip.into()) {
            Some(src_ip) => src_ip,
            None => {
                trace!("receive_icmp_echo_reply: unspecified source address");
                return Ok(());
            }
        };
        let src_ip: SocketIpAddr<_> = match src_ip.try_into() {
            Ok(src_ip) => src_ip,
            Err(AddrIsMappedError {}) => {
                trace!("receive_icmp_echo_reply: mapped source address");
                return Ok(());
            }
        };
        let dst_ip: SocketIpAddr<_> = match dst_ip.try_into() {
            Ok(dst_ip) => dst_ip,
            Err(AddrIsMappedError {}) => {
                trace!("receive_icmp_echo_reply: mapped destination address");
                return Ok(());
            }
        };

        core_ctx.with_icmp_ctx_and_sockets_mut(|_core_ctx, sockets| {
            let mut addrs_to_search = AddrVecIter::<I, CC::WeakDeviceId, IcmpAddrSpec>::with_device(
                ConnIpAddr { local: (dst_ip, id), remote: (src_ip, ()) }.into(),
                device.downgrade(),
            );
            let socket = match addrs_to_search.try_for_each(|addr_vec| {
                match addr_vec {
                    AddrVec::Conn(c) => {
                        if let Some(id) = sockets.socket_map.conns().get_by_addr(&c) {
                            return ControlFlow::Break(id);
                        }
                    }
                    AddrVec::Listen(l) => {
                        if let Some(id) = sockets.socket_map.listeners().get_by_addr(&l) {
                            return ControlFlow::Break(id);
                        }
                    }
                }
                ControlFlow::Continue(())
            }) {
                ControlFlow::Continue(()) => None,
                ControlFlow::Break(id) => Some(id),
            };
            if let Some(socket) = socket {
                trace!("receive_icmp_echo_reply: Received echo reply for local socket");
                bindings_ctx.receive_icmp_echo_reply(
                    socket,
                    device,
                    src_ip.addr(),
                    dst_ip.addr(),
                    id.get(),
                    buffer,
                );
                return;
            }
            // TODO(https://fxbug.dev/42124755): Neither the ICMPv4 or ICMPv6 RFCs
            // explicitly state what to do in case we receive an "unsolicited"
            // echo reply. We only expose the replies if we have a registered
            // connection for the IcmpAddr of the incoming reply for now. Given
            // that a reply should only be sent in response to a request, an
            // ICMP unreachable-type message is probably not appropriate for
            // unsolicited replies. However, it's also possible that we sent a
            // request and then closed the socket before receiving the reply, so
            // this doesn't necessarily indicate a buggy or malicious remote
            // host. We should figure this out definitively.
            //
            // If we do decide to send an ICMP error message, the appropriate
            // thing to do is probably to have this function return a `Result`,
            // and then have the top-level implementation of
            // `IpTransportContext::receive_ip_packet` return the
            // appropriate error.
            trace!("receive_icmp_echo_reply: Received echo reply with no local socket");
        });
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use alloc::rc::Rc;
    use alloc::vec;
    use core::cell::RefCell;
    use core::ops::{Deref, DerefMut};

    use assert_matches::assert_matches;
    use ip_test_macro::ip_test;
    use net_declare::net_ip_v6;
    use net_types::ip::Ipv6;
    use net_types::Witness;
    use netstack3_base::socket::StrictlyZonedAddr;
    use netstack3_base::testutil::{
        FakeBindingsCtx, FakeCoreCtx, FakeDeviceId, FakeWeakDeviceId, TestIpExt,
    };
    use netstack3_base::CtxPair;
    use netstack3_ip::socket::testutil::{FakeDeviceConfig, FakeIpSocketCtx, InnerFakeIpSocketCtx};
    use netstack3_ip::{ReceiveIpPacketMeta, SendIpPacketMeta};
    use packet::Buf;
    use packet_formats::icmp::{IcmpPacket, IcmpParseArgs, IcmpUnusedCode};

    use super::*;

    const REMOTE_ID: u16 = 27;
    const ICMP_ID: NonZeroU16 = const_unwrap::const_unwrap_option(NonZeroU16::new(10));
    const SEQ_NUM: u16 = 0xF0;

    /// Utilities for accessing locked internal state in tests.
    impl<I: IpExt, D: WeakDeviceIdentifier, BT: IcmpEchoBindingsTypes> IcmpSocketId<I, D, BT> {
        fn get(&self) -> impl Deref<Target = IcmpSocketState<I, D, BT>> + '_ {
            self.state().read()
        }

        fn get_mut(&self) -> impl DerefMut<Target = IcmpSocketState<I, D, BT>> + '_ {
            self.state().write()
        }
    }

    struct FakeIcmpCoreCtxState<I: IpExt> {
        bound_sockets:
            Rc<RefCell<BoundSockets<I, FakeWeakDeviceId<FakeDeviceId>, FakeIcmpBindingsCtx<I>>>>,
        all_sockets: IcmpSocketSet<I, FakeWeakDeviceId<FakeDeviceId>, FakeIcmpBindingsCtx<I>>,
        ip_socket_ctx: FakeIpSocketCtx<I, FakeDeviceId>,
        rx_counters: IcmpRxCounters<I>,
    }

    impl<I: IpExt> InnerFakeIpSocketCtx<I, FakeDeviceId> for FakeIcmpCoreCtxState<I> {
        fn fake_ip_socket_ctx_mut(&mut self) -> &mut FakeIpSocketCtx<I, FakeDeviceId> {
            &mut self.ip_socket_ctx
        }
    }

    impl<I: IpExt + TestIpExt> Default for FakeIcmpCoreCtxState<I> {
        fn default() -> Self {
            Self {
                bound_sockets: Default::default(),
                all_sockets: Default::default(),
                ip_socket_ctx: FakeIpSocketCtx::new(core::iter::once(FakeDeviceConfig {
                    device: FakeDeviceId,
                    local_ips: vec![I::TEST_ADDRS.local_ip],
                    remote_ips: vec![I::TEST_ADDRS.remote_ip],
                })),
                rx_counters: Default::default(),
            }
        }
    }

    type FakeIcmpCoreCtx<I> = FakeCoreCtx<
        FakeIcmpCoreCtxState<I>,
        SendIpPacketMeta<I, FakeDeviceId, SpecifiedAddr<<I as Ip>::Addr>>,
        FakeDeviceId,
    >;
    type FakeIcmpBindingsCtx<I> = FakeBindingsCtx<(), (), FakeIcmpBindingsCtxState<I>, ()>;
    type FakeIcmpCtx<I> = CtxPair<FakeIcmpCoreCtx<I>, FakeIcmpBindingsCtx<I>>;

    #[derive(Default)]
    struct FakeIcmpBindingsCtxState<I: IpExt> {
        received: Vec<ReceivedEchoPacket<I>>,
    }

    #[derive(Debug)]
    struct ReceivedEchoPacket<I: IpExt> {
        src_ip: I::Addr,
        dst_ip: I::Addr,
        socket: IcmpSocketId<I, FakeWeakDeviceId<FakeDeviceId>, FakeIcmpBindingsCtx<I>>,
        id: u16,
        data: Vec<u8>,
    }

    impl<I: IpExt> IcmpEchoContextMarker for FakeIcmpCoreCtx<I> {}

    impl<I: IpExt> CounterContext<IcmpRxCounters<I>> for FakeIcmpCoreCtxState<I> {
        fn with_counters<O, F: FnOnce(&IcmpRxCounters<I>) -> O>(&self, cb: F) -> O {
            cb(&self.rx_counters)
        }
    }

    impl<I: IpExt> IcmpEchoBoundStateContext<I, FakeIcmpBindingsCtx<I>> for FakeIcmpCoreCtx<I> {
        type IpSocketsCtx<'a> = Self;

        fn with_icmp_ctx_and_sockets_mut<
            O,
            F: FnOnce(
                &mut Self::IpSocketsCtx<'_>,
                &mut BoundSockets<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
            ) -> O,
        >(
            &mut self,
            cb: F,
        ) -> O {
            let bound_sockets = self.state.bound_sockets.clone();
            let mut bound_sockets = bound_sockets.borrow_mut();
            cb(self, &mut bound_sockets)
        }
    }

    impl<I: IpExt> IcmpEchoStateContext<I, FakeIcmpBindingsCtx<I>> for FakeIcmpCoreCtx<I> {
        type SocketStateCtx<'a> = Self;

        fn with_all_sockets_mut<
            O,
            F: FnOnce(&mut IcmpSocketSet<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>) -> O,
        >(
            &mut self,
            cb: F,
        ) -> O {
            cb(&mut self.state.all_sockets)
        }

        fn with_all_sockets<
            O,
            F: FnOnce(&IcmpSocketSet<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>) -> O,
        >(
            &mut self,
            cb: F,
        ) -> O {
            cb(&self.state.all_sockets)
        }

        fn with_socket_state<
            O,
            F: FnOnce(
                &mut Self::SocketStateCtx<'_>,
                &IcmpSocketState<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
            ) -> O,
        >(
            &mut self,
            id: &IcmpSocketId<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
            cb: F,
        ) -> O {
            cb(self, &id.get())
        }

        fn with_socket_state_mut<
            O,
            F: FnOnce(
                &mut Self::SocketStateCtx<'_>,
                &mut IcmpSocketState<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
            ) -> O,
        >(
            &mut self,
            id: &IcmpSocketId<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
            cb: F,
        ) -> O {
            cb(self, &mut id.get_mut())
        }

        fn with_bound_state_context<O, F: FnOnce(&mut Self::SocketStateCtx<'_>) -> O>(
            &mut self,
            cb: F,
        ) -> O {
            cb(self)
        }

        fn for_each_socket<
            F: FnMut(
                &mut Self::SocketStateCtx<'_>,
                &IcmpSocketId<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
                &IcmpSocketState<I, Self::WeakDeviceId, FakeIcmpBindingsCtx<I>>,
            ),
        >(
            &mut self,
            mut cb: F,
        ) {
            let socks = self
                .state
                .all_sockets
                .keys()
                .map(|id| IcmpSocketId::from(id.clone()))
                .collect::<Vec<_>>();
            for id in socks {
                cb(self, &id, &id.get());
            }
        }
    }

    impl<I: IpExt> IcmpEchoBindingsContext<I, FakeDeviceId> for FakeIcmpBindingsCtx<I> {
        fn receive_icmp_echo_reply<B: BufferMut>(
            &mut self,
            socket: &IcmpSocketId<I, FakeWeakDeviceId<FakeDeviceId>, FakeIcmpBindingsCtx<I>>,
            _device_id: &FakeDeviceId,
            src_ip: I::Addr,
            dst_ip: I::Addr,
            id: u16,
            data: B,
        ) {
            self.state.received.push(ReceivedEchoPacket {
                src_ip,
                dst_ip,
                id,
                data: data.to_flattened_vec(),
                socket: socket.clone(),
            })
        }
    }

    impl<I: IpExt> IcmpEchoBindingsTypes for FakeIcmpBindingsCtx<I> {
        type ExternalData<II: Ip> = ();
    }

    #[test]
    fn test_connect_dual_stack_fails() {
        // Verify that connecting to an ipv4-mapped-ipv6 address fails, as ICMP
        // sockets do not support dual-stack operations.
        let mut ctx = FakeIcmpCtx::<Ipv6>::default();
        let mut api = IcmpEchoSocketApi::<Ipv6, _>::new(ctx.as_mut());
        let conn = api.create();
        assert_eq!(
            api.connect(
                &conn,
                Some(ZonedAddr::Unzoned(
                    SpecifiedAddr::new(net_ip_v6!("::ffff:192.0.2.1")).unwrap(),
                )),
                REMOTE_ID,
            ),
            Err(datagram::ConnectError::RemoteUnexpectedlyMapped)
        );
    }

    #[ip_test(I)]
    fn send_invalid_icmp_echo<I: TestIpExt + IpExt>() {
        let mut ctx = FakeIcmpCtx::<I>::default();
        let mut api = IcmpEchoSocketApi::<I, _>::new(ctx.as_mut());
        let conn = api.create();
        api.connect(&conn, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), REMOTE_ID).unwrap();

        let buf = Buf::new(Vec::new(), ..)
            .encapsulate(IcmpPacketBuilder::<I, _>::new(
                I::TEST_ADDRS.local_ip.get(),
                I::TEST_ADDRS.remote_ip.get(),
                IcmpUnusedCode,
                packet_formats::icmp::IcmpEchoReply::new(0, 1),
            ))
            .serialize_vec_outer()
            .unwrap()
            .into_inner();
        assert_matches!(
            api.send(&conn, buf),
            Err(datagram::SendError::SerializeError(
                packet_formats::error::ParseError::NotExpected
            ))
        );
    }

    #[ip_test(I)]
    fn get_info<I: TestIpExt + IpExt>() {
        let mut ctx = FakeIcmpCtx::<I>::default();
        let mut api = IcmpEchoSocketApi::<I, _>::new(ctx.as_mut());

        let id = api.create();
        assert_eq!(api.get_info(&id), datagram::SocketInfo::Unbound);

        api.bind(&id, None, Some(ICMP_ID)).unwrap();
        assert_eq!(
            api.get_info(&id),
            datagram::SocketInfo::Listener(datagram::ListenerInfo {
                local_ip: None,
                local_identifier: ICMP_ID
            })
        );

        api.connect(&id, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), REMOTE_ID).unwrap();
        assert_eq!(
            api.get_info(&id),
            datagram::SocketInfo::Connected(datagram::ConnInfo {
                local_ip: StrictlyZonedAddr::new_unzoned_or_panic(I::TEST_ADDRS.local_ip),
                local_identifier: ICMP_ID,
                remote_ip: StrictlyZonedAddr::new_unzoned_or_panic(I::TEST_ADDRS.remote_ip),
                remote_identifier: REMOTE_ID,
            })
        );
    }

    #[ip_test(I)]
    fn send<I: TestIpExt + IpExt>() {
        let mut ctx = FakeIcmpCtx::<I>::default();
        let mut api = IcmpEchoSocketApi::<I, _>::new(ctx.as_mut());
        let sock = api.create();

        api.bind(&sock, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(ICMP_ID)).unwrap();
        api.connect(&sock, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.remote_ip)), REMOTE_ID).unwrap();

        let packet = Buf::new([1u8, 2, 3, 4], ..)
            .encapsulate(IcmpPacketBuilder::<I, _>::new(
                I::UNSPECIFIED_ADDRESS,
                I::UNSPECIFIED_ADDRESS,
                IcmpUnusedCode,
                // Use 0 here to show that this is filled by the API.
                IcmpEchoRequest::new(0, SEQ_NUM),
            ))
            .serialize_vec_outer()
            .unwrap()
            .unwrap_b();
        api.send(&sock, Buf::new(packet, ..)).unwrap();
        let frames = ctx.core_ctx.frames.take_frames();
        let (SendIpPacketMeta { device: _, src_ip, dst_ip, .. }, body) =
            assert_matches!(&frames[..], [f] => f);
        assert_eq!(dst_ip, &I::TEST_ADDRS.remote_ip);

        let mut body = &body[..];
        let echo_req: IcmpPacket<I, _, IcmpEchoRequest> =
            body.parse_with(IcmpParseArgs::new(src_ip.get(), dst_ip.get())).unwrap();
        assert_eq!(echo_req.message().id(), ICMP_ID.get());
        assert_eq!(echo_req.message().seq(), SEQ_NUM);
    }

    #[ip_test(I)]
    fn receive<I: TestIpExt + IpExt>() {
        let mut ctx = FakeIcmpCtx::<I>::default();
        let mut api = IcmpEchoSocketApi::<I, _>::new(ctx.as_mut());
        let sock = api.create();

        api.bind(&sock, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(ICMP_ID)).unwrap();

        let reply = Buf::new([1u8, 2, 3, 4], ..)
            .encapsulate(IcmpPacketBuilder::<I, _>::new(
                // Use whatever here this is not validated by this module.
                I::UNSPECIFIED_ADDRESS,
                I::UNSPECIFIED_ADDRESS,
                IcmpUnusedCode,
                IcmpEchoReply::new(ICMP_ID.get(), SEQ_NUM),
            ))
            .serialize_vec_outer()
            .unwrap();

        let CtxPair { core_ctx, bindings_ctx } = &mut ctx;
        let src_ip = I::TEST_ADDRS.remote_ip;
        let dst_ip = I::TEST_ADDRS.local_ip;
        <IcmpEchoIpTransportContext as IpTransportContext<I, _, _>>::receive_ip_packet(
            core_ctx,
            bindings_ctx,
            &FakeDeviceId,
            src_ip.get().try_into().unwrap(),
            dst_ip,
            reply.clone(),
            ReceiveIpPacketMeta::default(),
        )
        .unwrap();

        let received = core::mem::take(&mut bindings_ctx.state.received);
        let ReceivedEchoPacket {
            src_ip: got_src_ip,
            dst_ip: got_dst_ip,
            socket: got_socket,
            id: got_id,
            data: got_data,
        } = assert_matches!(&received[..], [f] => f);
        assert_eq!(got_src_ip, &src_ip.get());
        assert_eq!(got_dst_ip, &dst_ip.get());
        assert_eq!(got_socket, &sock);
        assert_eq!(got_id, &ICMP_ID.get());
        assert_eq!(&got_data[..], reply.as_ref());
    }

    #[ip_test(I)]
    fn receive_no_socket<I: TestIpExt + IpExt>() {
        let mut ctx = FakeIcmpCtx::<I>::default();
        let mut api = IcmpEchoSocketApi::<I, _>::new(ctx.as_mut());
        let sock = api.create();

        const BIND_ICMP_ID: NonZeroU16 = const_unwrap::const_unwrap_option(NonZeroU16::new(10));
        const OTHER_ICMP_ID: NonZeroU16 = const_unwrap::const_unwrap_option(NonZeroU16::new(16));

        api.bind(&sock, Some(ZonedAddr::Unzoned(I::TEST_ADDRS.local_ip)), Some(BIND_ICMP_ID))
            .unwrap();

        let reply = Buf::new(&mut [], ..)
            .encapsulate(IcmpPacketBuilder::<I, _>::new(
                // Use whatever here this is not validated by this module.
                I::UNSPECIFIED_ADDRESS,
                I::UNSPECIFIED_ADDRESS,
                IcmpUnusedCode,
                IcmpEchoReply::new(OTHER_ICMP_ID.get(), SEQ_NUM),
            ))
            .serialize_vec_outer()
            .unwrap();

        let CtxPair { core_ctx, bindings_ctx } = &mut ctx;
        <IcmpEchoIpTransportContext as IpTransportContext<I, _, _>>::receive_ip_packet(
            core_ctx,
            bindings_ctx,
            &FakeDeviceId,
            I::TEST_ADDRS.remote_ip.get().try_into().unwrap(),
            I::TEST_ADDRS.local_ip,
            reply,
            ReceiveIpPacketMeta::default(),
        )
        .unwrap();
        assert_matches!(&bindings_ctx.state.received[..], []);
    }

    #[ip_test(I)]
    #[test_case::test_matrix(
        [MarkDomain::Mark1, MarkDomain::Mark2],
        [None, Some(0), Some(1)]
    )]
    fn icmp_socket_marks<I: TestIpExt + IpExt>(domain: MarkDomain, mark: Option<u32>) {
        let mut ctx = FakeIcmpCtx::<I>::default();
        let mut api = IcmpEchoSocketApi::<I, _>::new(ctx.as_mut());
        let socket = api.create();

        // Doesn't have a mark by default.
        assert_eq!(api.get_mark(&socket, domain), Mark(None));

        let mark = Mark(mark);
        // We can set and get back the mark.
        api.set_mark(&socket, domain, mark);
        assert_eq!(api.get_mark(&socket, domain), mark);
    }
}