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
use core::cmp;
#[cfg(feature = "async")]
use core::task::Waker;

use crate::phy::ChecksumCapabilities;
#[cfg(feature = "async")]
use crate::socket::WakerRegistration;
use crate::socket::{Context, PollAt};
use crate::storage::{PacketBuffer, PacketMetadata};
use crate::{Error, Result};

use crate::wire::IcmpRepr;
#[cfg(feature = "proto-ipv4")]
use crate::wire::{Icmpv4Packet, Icmpv4Repr, Ipv4Address, Ipv4Repr};
#[cfg(feature = "proto-ipv6")]
use crate::wire::{Icmpv6Packet, Icmpv6Repr, Ipv6Address, Ipv6Repr};
use crate::wire::{IpAddress, IpEndpoint, IpProtocol, IpRepr};
use crate::wire::{UdpPacket, UdpRepr};

/// Type of endpoint to bind the ICMP socket to. See [IcmpSocket::bind] for
/// more details.
///
/// [IcmpSocket::bind]: struct.IcmpSocket.html#method.bind
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Endpoint {
    Unspecified,
    Ident(u16),
    Udp(IpEndpoint),
}

impl Endpoint {
    pub fn is_specified(&self) -> bool {
        match *self {
            Endpoint::Ident(_) => true,
            Endpoint::Udp(endpoint) => endpoint.port != 0,
            Endpoint::Unspecified => false,
        }
    }
}

impl Default for Endpoint {
    fn default() -> Endpoint {
        Endpoint::Unspecified
    }
}

/// An ICMP packet metadata.
pub type IcmpPacketMetadata = PacketMetadata<IpAddress>;

/// An ICMP packet ring buffer.
pub type IcmpSocketBuffer<'a> = PacketBuffer<'a, IpAddress>;

/// A ICMP socket
///
/// An ICMP socket is bound to a specific [IcmpEndpoint] which may
/// be a sepecific UDP port to listen for ICMP error messages related
/// to the port or a specific ICMP identifier value. See [bind] for
/// more details.
///
/// [IcmpEndpoint]: enum.IcmpEndpoint.html
/// [bind]: #method.bind
#[derive(Debug)]
pub struct IcmpSocket<'a> {
    rx_buffer: IcmpSocketBuffer<'a>,
    tx_buffer: IcmpSocketBuffer<'a>,
    /// The endpoint this socket is communicating with
    endpoint: Endpoint,
    /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
    hop_limit: Option<u8>,
    #[cfg(feature = "async")]
    rx_waker: WakerRegistration,
    #[cfg(feature = "async")]
    tx_waker: WakerRegistration,
}

impl<'a> IcmpSocket<'a> {
    /// Create an ICMP socket with the given buffers.
    pub fn new(rx_buffer: IcmpSocketBuffer<'a>, tx_buffer: IcmpSocketBuffer<'a>) -> IcmpSocket<'a> {
        IcmpSocket {
            rx_buffer: rx_buffer,
            tx_buffer: tx_buffer,
            endpoint: Endpoint::default(),
            hop_limit: None,
            #[cfg(feature = "async")]
            rx_waker: WakerRegistration::new(),
            #[cfg(feature = "async")]
            tx_waker: WakerRegistration::new(),
        }
    }

    /// Register a waker for receive operations.
    ///
    /// The waker is woken on state changes that might affect the return value
    /// of `recv` method calls, such as receiving data, or the socket closing.
    ///
    /// Notes:
    ///
    /// - Only one waker can be registered at a time. If another waker was previously registered,
    ///   it is overwritten and will no longer be woken.
    /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
    /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
    ///   necessarily changed.
    #[cfg(feature = "async")]
    pub fn register_recv_waker(&mut self, waker: &Waker) {
        self.rx_waker.register(waker)
    }

    /// Register a waker for send operations.
    ///
    /// The waker is woken on state changes that might affect the return value
    /// of `send` method calls, such as space becoming available in the transmit
    /// buffer, or the socket closing.
    ///
    /// Notes:
    ///
    /// - Only one waker can be registered at a time. If another waker was previously registered,
    ///   it is overwritten and will no longer be woken.
    /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
    /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
    ///   necessarily changed.
    #[cfg(feature = "async")]
    pub fn register_send_waker(&mut self, waker: &Waker) {
        self.tx_waker.register(waker)
    }

    /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
    ///
    /// See also the [set_hop_limit](#method.set_hop_limit) method
    pub fn hop_limit(&self) -> Option<u8> {
        self.hop_limit
    }

    /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
    ///
    /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
    /// value (64).
    ///
    /// # Panics
    ///
    /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
    ///
    /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
    /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
    pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
        // A host MUST NOT send a datagram with a hop limit value of 0
        if let Some(0) = hop_limit {
            panic!("the time-to-live value of a packet must not be zero")
        }

        self.hop_limit = hop_limit
    }

    /// Bind the socket to the given endpoint.
    ///
    /// This function returns `Err(Error::Illegal)` if the socket was open
    /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
    /// if `endpoint` is unspecified (see [is_specified]).
    ///
    /// # Examples
    ///
    /// ## Bind to ICMP Error messages associated with a specific UDP port:
    ///
    /// To [recv] ICMP error messages that are associated with a specific local
    /// UDP port, the socket may be bound to a given port using [IcmpEndpoint::Udp].
    /// This may be useful for applications using UDP attempting to detect and/or
    /// diagnose connection problems.
    ///
    /// ```
    /// # use smoltcp::socket::{Socket, IcmpSocket, IcmpSocketBuffer, IcmpPacketMetadata};
    /// # let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 20]);
    /// # let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 20]);
    /// use smoltcp::wire::IpEndpoint;
    /// use smoltcp::socket::IcmpEndpoint;
    ///
    /// let mut icmp_socket = // ...
    /// # IcmpSocket::new(rx_buffer, tx_buffer);
    ///
    /// // Bind to ICMP error responses for UDP packets sent from port 53.
    /// let endpoint = IpEndpoint::from(53);
    /// icmp_socket.bind(IcmpEndpoint::Udp(endpoint)).unwrap();
    /// ```
    ///
    /// ## Bind to a specific ICMP identifier:
    ///
    /// To [send] and [recv] ICMP packets that are not associated with a specific UDP
    /// port, the socket may be bound to a specific ICMP identifier using
    /// [IcmpEndpoint::Ident]. This is useful for sending and receiving Echo Request/Reply
    /// messages.
    ///
    /// ```
    /// # use smoltcp::socket::{Socket, IcmpSocket, IcmpSocketBuffer, IcmpPacketMetadata};
    /// # let rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 20]);
    /// # let tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 20]);
    /// use smoltcp::socket::IcmpEndpoint;
    ///
    /// let mut icmp_socket = // ...
    /// # IcmpSocket::new(rx_buffer, tx_buffer);
    ///
    /// // Bind to ICMP messages with the ICMP identifier 0x1234
    /// icmp_socket.bind(IcmpEndpoint::Ident(0x1234)).unwrap();
    /// ```
    ///
    /// [is_specified]: enum.IcmpEndpoint.html#method.is_specified
    /// [IcmpEndpoint::Ident]: enum.IcmpEndpoint.html#variant.Ident
    /// [IcmpEndpoint::Udp]: enum.IcmpEndpoint.html#variant.Udp
    /// [send]: #method.send
    /// [recv]: #method.recv
    pub fn bind<T: Into<Endpoint>>(&mut self, endpoint: T) -> Result<()> {
        let endpoint = endpoint.into();
        if !endpoint.is_specified() {
            return Err(Error::Unaddressable);
        }

        if self.is_open() {
            return Err(Error::Illegal);
        }

        self.endpoint = endpoint;

        #[cfg(feature = "async")]
        {
            self.rx_waker.wake();
            self.tx_waker.wake();
        }

        Ok(())
    }

    /// Check whether the transmit buffer is full.
    #[inline]
    pub fn can_send(&self) -> bool {
        !self.tx_buffer.is_full()
    }

    /// Check whether the receive buffer is not empty.
    #[inline]
    pub fn can_recv(&self) -> bool {
        !self.rx_buffer.is_empty()
    }

    /// Return the maximum number packets the socket can receive.
    #[inline]
    pub fn packet_recv_capacity(&self) -> usize {
        self.rx_buffer.packet_capacity()
    }

    /// Return the maximum number packets the socket can transmit.
    #[inline]
    pub fn packet_send_capacity(&self) -> usize {
        self.tx_buffer.packet_capacity()
    }

    /// Return the maximum number of bytes inside the recv buffer.
    #[inline]
    pub fn payload_recv_capacity(&self) -> usize {
        self.rx_buffer.payload_capacity()
    }

    /// Return the maximum number of bytes inside the transmit buffer.
    #[inline]
    pub fn payload_send_capacity(&self) -> usize {
        self.tx_buffer.payload_capacity()
    }

    /// Check whether the socket is open.
    #[inline]
    pub fn is_open(&self) -> bool {
        self.endpoint != Endpoint::Unspecified
    }

    /// Enqueue a packet to be sent to a given remote address, and return a pointer
    /// to its payload.
    ///
    /// This function returns `Err(Error::Exhausted)` if the transmit buffer is full,
    /// `Err(Error::Truncated)` if the requested size is larger than the packet buffer
    /// size, and `Err(Error::Unaddressable)` if the remote address is unspecified.
    pub fn send(&mut self, size: usize, endpoint: IpAddress) -> Result<&mut [u8]> {
        if endpoint.is_unspecified() {
            return Err(Error::Unaddressable);
        }

        let packet_buf = self.tx_buffer.enqueue(size, endpoint)?;

        net_trace!("icmp:{}: buffer to send {} octets", endpoint, size);
        Ok(packet_buf)
    }

    /// Enqueue a packet to be sent to a given remote address, and fill it from a slice.
    ///
    /// See also [send](#method.send).
    pub fn send_slice(&mut self, data: &[u8], endpoint: IpAddress) -> Result<()> {
        let packet_buf = self.send(data.len(), endpoint)?;
        packet_buf.copy_from_slice(data);
        Ok(())
    }

    /// Dequeue a packet received from a remote endpoint, and return the `IpAddress` as well
    /// as a pointer to the payload.
    ///
    /// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
    pub fn recv(&mut self) -> Result<(&[u8], IpAddress)> {
        let (endpoint, packet_buf) = self.rx_buffer.dequeue()?;

        net_trace!(
            "icmp:{}: receive {} buffered octets",
            endpoint,
            packet_buf.len()
        );
        Ok((packet_buf, endpoint))
    }

    /// Dequeue a packet received from a remote endpoint, copy the payload into the given slice,
    /// and return the amount of octets copied as well as the `IpAddress`
    ///
    /// See also [recv](#method.recv).
    pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(usize, IpAddress)> {
        let (buffer, endpoint) = self.recv()?;
        let length = cmp::min(data.len(), buffer.len());
        data[..length].copy_from_slice(&buffer[..length]);
        Ok((length, endpoint))
    }

    /// Filter determining which packets received by the interface are appended to
    /// the given sockets received buffer.
    pub(crate) fn accepts(&self, cx: &mut Context, ip_repr: &IpRepr, icmp_repr: &IcmpRepr) -> bool {
        match (&self.endpoint, icmp_repr) {
            // If we are bound to ICMP errors associated to a UDP port, only
            // accept Destination Unreachable messages with the data containing
            // a UDP packet send from the local port we are bound to.
            #[cfg(feature = "proto-ipv4")]
            (
                &Endpoint::Udp(endpoint),
                &IcmpRepr::Ipv4(Icmpv4Repr::DstUnreachable { data, .. }),
            ) if endpoint.addr.is_unspecified() || endpoint.addr == ip_repr.dst_addr() => {
                let packet = UdpPacket::new_unchecked(data);
                match UdpRepr::parse(
                    &packet,
                    &ip_repr.src_addr(),
                    &ip_repr.dst_addr(),
                    &cx.checksum_caps(),
                ) {
                    Ok(repr) => endpoint.port == repr.src_port,
                    Err(_) => false,
                }
            }
            #[cfg(feature = "proto-ipv6")]
            (
                &Endpoint::Udp(endpoint),
                &IcmpRepr::Ipv6(Icmpv6Repr::DstUnreachable { data, .. }),
            ) if endpoint.addr.is_unspecified() || endpoint.addr == ip_repr.dst_addr() => {
                let packet = UdpPacket::new_unchecked(data);
                match UdpRepr::parse(
                    &packet,
                    &ip_repr.src_addr(),
                    &ip_repr.dst_addr(),
                    &cx.checksum_caps(),
                ) {
                    Ok(repr) => endpoint.port == repr.src_port,
                    Err(_) => false,
                }
            }
            // If we are bound to a specific ICMP identifier value, only accept an
            // Echo Request/Reply with the identifier field matching the endpoint
            // port.
            #[cfg(feature = "proto-ipv4")]
            (
                &Endpoint::Ident(bound_ident),
                &IcmpRepr::Ipv4(Icmpv4Repr::EchoRequest { ident, .. }),
            )
            | (
                &Endpoint::Ident(bound_ident),
                &IcmpRepr::Ipv4(Icmpv4Repr::EchoReply { ident, .. }),
            ) => ident == bound_ident,
            #[cfg(feature = "proto-ipv6")]
            (
                &Endpoint::Ident(bound_ident),
                &IcmpRepr::Ipv6(Icmpv6Repr::EchoRequest { ident, .. }),
            )
            | (
                &Endpoint::Ident(bound_ident),
                &IcmpRepr::Ipv6(Icmpv6Repr::EchoReply { ident, .. }),
            ) => ident == bound_ident,
            _ => false,
        }
    }

    pub(crate) fn process(
        &mut self,
        _cx: &mut Context,
        ip_repr: &IpRepr,
        icmp_repr: &IcmpRepr,
    ) -> Result<()> {
        match *icmp_repr {
            #[cfg(feature = "proto-ipv4")]
            IcmpRepr::Ipv4(ref icmp_repr) => {
                let packet_buf = self
                    .rx_buffer
                    .enqueue(icmp_repr.buffer_len(), ip_repr.src_addr())?;
                icmp_repr.emit(
                    &mut Icmpv4Packet::new_unchecked(packet_buf),
                    &ChecksumCapabilities::default(),
                );

                net_trace!(
                    "icmp:{}: receiving {} octets",
                    icmp_repr.buffer_len(),
                    packet_buf.len()
                );
            }
            #[cfg(feature = "proto-ipv6")]
            IcmpRepr::Ipv6(ref icmp_repr) => {
                let packet_buf = self
                    .rx_buffer
                    .enqueue(icmp_repr.buffer_len(), ip_repr.src_addr())?;
                icmp_repr.emit(
                    &ip_repr.src_addr(),
                    &ip_repr.dst_addr(),
                    &mut Icmpv6Packet::new_unchecked(packet_buf),
                    &ChecksumCapabilities::default(),
                );

                net_trace!(
                    "icmp:{}: receiving {} octets",
                    icmp_repr.buffer_len(),
                    packet_buf.len()
                );
            }
        }

        #[cfg(feature = "async")]
        self.rx_waker.wake();

        Ok(())
    }

    pub(crate) fn dispatch<F>(&mut self, cx: &mut Context, emit: F) -> Result<()>
    where
        F: FnOnce(&mut Context, (IpRepr, IcmpRepr)) -> Result<()>,
    {
        let hop_limit = self.hop_limit.unwrap_or(64);
        self.tx_buffer.dequeue_with(|remote_endpoint, packet_buf| {
            net_trace!(
                "icmp:{}: sending {} octets",
                remote_endpoint,
                packet_buf.len()
            );
            match *remote_endpoint {
                #[cfg(feature = "proto-ipv4")]
                IpAddress::Ipv4(ipv4_addr) => {
                    let packet = Icmpv4Packet::new_unchecked(&*packet_buf);
                    let repr = Icmpv4Repr::parse(&packet, &ChecksumCapabilities::ignored())?;
                    let ip_repr = IpRepr::Ipv4(Ipv4Repr {
                        src_addr: Ipv4Address::default(),
                        dst_addr: ipv4_addr,
                        protocol: IpProtocol::Icmp,
                        payload_len: repr.buffer_len(),
                        hop_limit: hop_limit,
                    });
                    emit(cx, (ip_repr, IcmpRepr::Ipv4(repr)))
                }
                #[cfg(feature = "proto-ipv6")]
                IpAddress::Ipv6(ipv6_addr) => {
                    let packet = Icmpv6Packet::new_unchecked(&*packet_buf);
                    let src_addr = Ipv6Address::default();
                    let repr = Icmpv6Repr::parse(
                        &src_addr.into(),
                        &ipv6_addr.into(),
                        &packet,
                        &ChecksumCapabilities::ignored(),
                    )?;
                    let ip_repr = IpRepr::Ipv6(Ipv6Repr {
                        src_addr: src_addr,
                        dst_addr: ipv6_addr,
                        next_header: IpProtocol::Icmpv6,
                        payload_len: repr.buffer_len(),
                        hop_limit: hop_limit,
                    });
                    emit(cx, (ip_repr, IcmpRepr::Ipv6(repr)))
                }
                _ => Err(Error::Unaddressable),
            }
        })?;

        #[cfg(feature = "async")]
        self.tx_waker.wake();

        Ok(())
    }

    pub(crate) fn poll_at(&self, _cx: &mut Context) -> PollAt {
        if self.tx_buffer.is_empty() {
            PollAt::Ingress
        } else {
            PollAt::Now
        }
    }
}

#[cfg(test)]
mod tests_common {
    pub use super::*;
    pub use crate::phy::DeviceCapabilities;
    pub use crate::wire::IpAddress;

    pub fn buffer(packets: usize) -> IcmpSocketBuffer<'static> {
        IcmpSocketBuffer::new(
            vec![IcmpPacketMetadata::EMPTY; packets],
            vec![0; 66 * packets],
        )
    }

    pub fn socket(
        rx_buffer: IcmpSocketBuffer<'static>,
        tx_buffer: IcmpSocketBuffer<'static>,
    ) -> IcmpSocket<'static> {
        IcmpSocket::new(rx_buffer, tx_buffer)
    }

    pub const LOCAL_PORT: u16 = 53;

    pub static UDP_REPR: UdpRepr = UdpRepr {
        src_port: 53,
        dst_port: 9090,
    };

    pub static UDP_PAYLOAD: &[u8] = &[0xff; 10];
}

#[cfg(all(test, feature = "proto-ipv4"))]
mod test_ipv4 {
    use super::tests_common::*;

    use crate::wire::Icmpv4DstUnreachable;

    const REMOTE_IPV4: Ipv4Address = Ipv4Address([0x7f, 0x00, 0x00, 0x02]);
    const LOCAL_IPV4: Ipv4Address = Ipv4Address([0x7f, 0x00, 0x00, 0x01]);
    const LOCAL_END_V4: IpEndpoint = IpEndpoint {
        addr: IpAddress::Ipv4(LOCAL_IPV4),
        port: LOCAL_PORT,
    };

    static ECHOV4_REPR: Icmpv4Repr = Icmpv4Repr::EchoRequest {
        ident: 0x1234,
        seq_no: 0x5678,
        data: &[0xff; 16],
    };

    static LOCAL_IPV4_REPR: IpRepr = IpRepr::Ipv4(Ipv4Repr {
        src_addr: Ipv4Address::UNSPECIFIED,
        dst_addr: REMOTE_IPV4,
        protocol: IpProtocol::Icmp,
        payload_len: 24,
        hop_limit: 0x40,
    });

    static REMOTE_IPV4_REPR: IpRepr = IpRepr::Ipv4(Ipv4Repr {
        src_addr: REMOTE_IPV4,
        dst_addr: LOCAL_IPV4,
        protocol: IpProtocol::Icmp,
        payload_len: 24,
        hop_limit: 0x40,
    });

    #[test]
    fn test_send_unaddressable() {
        let mut socket = socket(buffer(0), buffer(1));
        assert_eq!(
            socket.send_slice(b"abcdef", IpAddress::default()),
            Err(Error::Unaddressable)
        );
        assert_eq!(socket.send_slice(b"abcdef", REMOTE_IPV4.into()), Ok(()));
    }

    #[test]
    fn test_send_dispatch() {
        let mut socket = socket(buffer(0), buffer(1));
        let mut cx = Context::mock();
        let checksum = ChecksumCapabilities::default();

        assert_eq!(
            socket.dispatch(&mut cx, |_, _| unreachable!()),
            Err(Error::Exhausted)
        );

        // This buffer is too long
        assert_eq!(
            socket.send_slice(&[0xff; 67], REMOTE_IPV4.into()),
            Err(Error::Truncated)
        );
        assert!(socket.can_send());

        let mut bytes = [0xff; 24];
        let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
        ECHOV4_REPR.emit(&mut packet, &checksum);

        assert_eq!(
            socket.send_slice(&packet.into_inner()[..], REMOTE_IPV4.into()),
            Ok(())
        );
        assert_eq!(
            socket.send_slice(b"123456", REMOTE_IPV4.into()),
            Err(Error::Exhausted)
        );
        assert!(!socket.can_send());

        assert_eq!(
            socket.dispatch(&mut cx, |_, (ip_repr, icmp_repr)| {
                assert_eq!(ip_repr, LOCAL_IPV4_REPR);
                assert_eq!(icmp_repr, ECHOV4_REPR.into());
                Err(Error::Unaddressable)
            }),
            Err(Error::Unaddressable)
        );
        // buffer is not taken off of the tx queue due to the error
        assert!(!socket.can_send());

        assert_eq!(
            socket.dispatch(&mut cx, |_, (ip_repr, icmp_repr)| {
                assert_eq!(ip_repr, LOCAL_IPV4_REPR);
                assert_eq!(icmp_repr, ECHOV4_REPR.into());
                Ok(())
            }),
            Ok(())
        );
        // buffer is taken off of the queue this time
        assert!(socket.can_send());
    }

    #[test]
    fn test_set_hop_limit_v4() {
        let mut s = socket(buffer(0), buffer(1));
        let mut cx = Context::mock();
        let checksum = ChecksumCapabilities::default();

        let mut bytes = [0xff; 24];
        let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
        ECHOV4_REPR.emit(&mut packet, &checksum);

        s.set_hop_limit(Some(0x2a));

        assert_eq!(
            s.send_slice(&packet.into_inner()[..], REMOTE_IPV4.into()),
            Ok(())
        );
        assert_eq!(
            s.dispatch(&mut cx, |_, (ip_repr, _)| {
                assert_eq!(
                    ip_repr,
                    IpRepr::Ipv4(Ipv4Repr {
                        src_addr: Ipv4Address::UNSPECIFIED,
                        dst_addr: REMOTE_IPV4,
                        protocol: IpProtocol::Icmp,
                        payload_len: ECHOV4_REPR.buffer_len(),
                        hop_limit: 0x2a,
                    })
                );
                Ok(())
            }),
            Ok(())
        );
    }

    #[test]
    fn test_recv_process() {
        let mut socket = socket(buffer(1), buffer(1));
        let mut cx = Context::mock();
        assert_eq!(socket.bind(Endpoint::Ident(0x1234)), Ok(()));

        assert!(!socket.can_recv());
        assert_eq!(socket.recv(), Err(Error::Exhausted));

        let checksum = ChecksumCapabilities::default();

        let mut bytes = [0xff; 24];
        let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
        ECHOV4_REPR.emit(&mut packet, &checksum);
        let data = &packet.into_inner()[..];

        assert!(socket.accepts(&mut cx, &REMOTE_IPV4_REPR, &ECHOV4_REPR.into()));
        assert_eq!(
            socket.process(&mut cx, &REMOTE_IPV4_REPR, &ECHOV4_REPR.into()),
            Ok(())
        );
        assert!(socket.can_recv());

        assert!(socket.accepts(&mut cx, &REMOTE_IPV4_REPR, &ECHOV4_REPR.into()));
        assert_eq!(
            socket.process(&mut cx, &REMOTE_IPV4_REPR, &ECHOV4_REPR.into()),
            Err(Error::Exhausted)
        );

        assert_eq!(socket.recv(), Ok((data, REMOTE_IPV4.into())));
        assert!(!socket.can_recv());
    }

    #[test]
    fn test_accept_bad_id() {
        let mut socket = socket(buffer(1), buffer(1));
        let mut cx = Context::mock();
        assert_eq!(socket.bind(Endpoint::Ident(0x1234)), Ok(()));

        let checksum = ChecksumCapabilities::default();
        let mut bytes = [0xff; 20];
        let mut packet = Icmpv4Packet::new_unchecked(&mut bytes);
        let icmp_repr = Icmpv4Repr::EchoRequest {
            ident: 0x4321,
            seq_no: 0x5678,
            data: &[0xff; 16],
        };
        icmp_repr.emit(&mut packet, &checksum);

        // Ensure that a packet with an identifier that isn't the bound
        // ID is not accepted
        assert!(!socket.accepts(&mut cx, &REMOTE_IPV4_REPR, &icmp_repr.into()));
    }

    #[test]
    fn test_accepts_udp() {
        let mut socket = socket(buffer(1), buffer(1));
        let mut cx = Context::mock();
        assert_eq!(socket.bind(Endpoint::Udp(LOCAL_END_V4)), Ok(()));

        let checksum = ChecksumCapabilities::default();

        let mut bytes = [0xff; 18];
        let mut packet = UdpPacket::new_unchecked(&mut bytes);
        UDP_REPR.emit(
            &mut packet,
            &REMOTE_IPV4.into(),
            &LOCAL_IPV4.into(),
            UDP_PAYLOAD.len(),
            |buf| buf.copy_from_slice(UDP_PAYLOAD),
            &checksum,
        );

        let data = &packet.into_inner()[..];

        let icmp_repr = Icmpv4Repr::DstUnreachable {
            reason: Icmpv4DstUnreachable::PortUnreachable,
            header: Ipv4Repr {
                src_addr: LOCAL_IPV4,
                dst_addr: REMOTE_IPV4,
                protocol: IpProtocol::Icmp,
                payload_len: 12,
                hop_limit: 0x40,
            },
            data: data,
        };
        let ip_repr = IpRepr::Unspecified {
            src_addr: REMOTE_IPV4.into(),
            dst_addr: LOCAL_IPV4.into(),
            protocol: IpProtocol::Icmp,
            payload_len: icmp_repr.buffer_len(),
            hop_limit: 0x40,
        };

        assert!(!socket.can_recv());

        // Ensure we can accept ICMP error response to the bound
        // UDP port
        assert!(socket.accepts(&mut cx, &ip_repr, &icmp_repr.into()));
        assert_eq!(socket.process(&mut cx, &ip_repr, &icmp_repr.into()), Ok(()));
        assert!(socket.can_recv());

        let mut bytes = [0x00; 46];
        let mut packet = Icmpv4Packet::new_unchecked(&mut bytes[..]);
        icmp_repr.emit(&mut packet, &checksum);
        assert_eq!(
            socket.recv(),
            Ok((&packet.into_inner()[..], REMOTE_IPV4.into()))
        );
        assert!(!socket.can_recv());
    }
}

#[cfg(all(test, feature = "proto-ipv6"))]
mod test_ipv6 {
    use super::tests_common::*;

    use crate::wire::Icmpv6DstUnreachable;

    const REMOTE_IPV6: Ipv6Address =
        Ipv6Address([0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
    const LOCAL_IPV6: Ipv6Address =
        Ipv6Address([0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]);
    const LOCAL_END_V6: IpEndpoint = IpEndpoint {
        addr: IpAddress::Ipv6(LOCAL_IPV6),
        port: LOCAL_PORT,
    };
    static ECHOV6_REPR: Icmpv6Repr = Icmpv6Repr::EchoRequest {
        ident: 0x1234,
        seq_no: 0x5678,
        data: &[0xff; 16],
    };

    static LOCAL_IPV6_REPR: IpRepr = IpRepr::Ipv6(Ipv6Repr {
        src_addr: Ipv6Address::UNSPECIFIED,
        dst_addr: REMOTE_IPV6,
        next_header: IpProtocol::Icmpv6,
        payload_len: 24,
        hop_limit: 0x40,
    });

    static REMOTE_IPV6_REPR: IpRepr = IpRepr::Ipv6(Ipv6Repr {
        src_addr: REMOTE_IPV6,
        dst_addr: LOCAL_IPV6,
        next_header: IpProtocol::Icmpv6,
        payload_len: 24,
        hop_limit: 0x40,
    });

    #[test]
    fn test_send_unaddressable() {
        let mut socket = socket(buffer(0), buffer(1));
        assert_eq!(
            socket.send_slice(b"abcdef", IpAddress::default()),
            Err(Error::Unaddressable)
        );
        assert_eq!(socket.send_slice(b"abcdef", REMOTE_IPV6.into()), Ok(()));
    }

    #[test]
    fn test_send_dispatch() {
        let mut socket = socket(buffer(0), buffer(1));
        let mut cx = Context::mock();
        let checksum = ChecksumCapabilities::default();

        assert_eq!(
            socket.dispatch(&mut cx, |_, _| unreachable!()),
            Err(Error::Exhausted)
        );

        // This buffer is too long
        assert_eq!(
            socket.send_slice(&[0xff; 67], REMOTE_IPV6.into()),
            Err(Error::Truncated)
        );
        assert!(socket.can_send());

        let mut bytes = vec![0xff; 24];
        let mut packet = Icmpv6Packet::new_unchecked(&mut bytes);
        ECHOV6_REPR.emit(
            &LOCAL_IPV6.into(),
            &REMOTE_IPV6.into(),
            &mut packet,
            &checksum,
        );

        assert_eq!(
            socket.send_slice(&packet.into_inner()[..], REMOTE_IPV6.into()),
            Ok(())
        );
        assert_eq!(
            socket.send_slice(b"123456", REMOTE_IPV6.into()),
            Err(Error::Exhausted)
        );
        assert!(!socket.can_send());

        assert_eq!(
            socket.dispatch(&mut cx, |_, (ip_repr, icmp_repr)| {
                assert_eq!(ip_repr, LOCAL_IPV6_REPR);
                assert_eq!(icmp_repr, ECHOV6_REPR.into());
                Err(Error::Unaddressable)
            }),
            Err(Error::Unaddressable)
        );
        // buffer is not taken off of the tx queue due to the error
        assert!(!socket.can_send());

        assert_eq!(
            socket.dispatch(&mut cx, |_, (ip_repr, icmp_repr)| {
                assert_eq!(ip_repr, LOCAL_IPV6_REPR);
                assert_eq!(icmp_repr, ECHOV6_REPR.into());
                Ok(())
            }),
            Ok(())
        );
        // buffer is taken off of the queue this time
        assert!(socket.can_send());
    }

    #[test]
    fn test_set_hop_limit() {
        let mut s = socket(buffer(0), buffer(1));
        let mut cx = Context::mock();
        let checksum = ChecksumCapabilities::default();

        let mut bytes = vec![0xff; 24];
        let mut packet = Icmpv6Packet::new_unchecked(&mut bytes);
        ECHOV6_REPR.emit(
            &LOCAL_IPV6.into(),
            &REMOTE_IPV6.into(),
            &mut packet,
            &checksum,
        );

        s.set_hop_limit(Some(0x2a));

        assert_eq!(
            s.send_slice(&packet.into_inner()[..], REMOTE_IPV6.into()),
            Ok(())
        );
        assert_eq!(
            s.dispatch(&mut cx, |_, (ip_repr, _)| {
                assert_eq!(
                    ip_repr,
                    IpRepr::Ipv6(Ipv6Repr {
                        src_addr: Ipv6Address::UNSPECIFIED,
                        dst_addr: REMOTE_IPV6,
                        next_header: IpProtocol::Icmpv6,
                        payload_len: ECHOV6_REPR.buffer_len(),
                        hop_limit: 0x2a,
                    })
                );
                Ok(())
            }),
            Ok(())
        );
    }

    #[test]
    fn test_recv_process() {
        let mut socket = socket(buffer(1), buffer(1));
        let mut cx = Context::mock();
        assert_eq!(socket.bind(Endpoint::Ident(0x1234)), Ok(()));

        assert!(!socket.can_recv());
        assert_eq!(socket.recv(), Err(Error::Exhausted));

        let checksum = ChecksumCapabilities::default();

        let mut bytes = [0xff; 24];
        let mut packet = Icmpv6Packet::new_unchecked(&mut bytes);
        ECHOV6_REPR.emit(
            &LOCAL_IPV6.into(),
            &REMOTE_IPV6.into(),
            &mut packet,
            &checksum,
        );
        let data = &packet.into_inner()[..];

        assert!(socket.accepts(&mut cx, &REMOTE_IPV6_REPR, &ECHOV6_REPR.into()));
        assert_eq!(
            socket.process(&mut cx, &REMOTE_IPV6_REPR, &ECHOV6_REPR.into()),
            Ok(())
        );
        assert!(socket.can_recv());

        assert!(socket.accepts(&mut cx, &REMOTE_IPV6_REPR, &ECHOV6_REPR.into()));
        assert_eq!(
            socket.process(&mut cx, &REMOTE_IPV6_REPR, &ECHOV6_REPR.into()),
            Err(Error::Exhausted)
        );

        assert_eq!(socket.recv(), Ok((data, REMOTE_IPV6.into())));
        assert!(!socket.can_recv());
    }

    #[test]
    fn test_accept_bad_id() {
        let mut socket = socket(buffer(1), buffer(1));
        let mut cx = Context::mock();
        assert_eq!(socket.bind(Endpoint::Ident(0x1234)), Ok(()));

        let checksum = ChecksumCapabilities::default();
        let mut bytes = [0xff; 20];
        let mut packet = Icmpv6Packet::new_unchecked(&mut bytes);
        let icmp_repr = Icmpv6Repr::EchoRequest {
            ident: 0x4321,
            seq_no: 0x5678,
            data: &[0xff; 16],
        };
        icmp_repr.emit(
            &LOCAL_IPV6.into(),
            &REMOTE_IPV6.into(),
            &mut packet,
            &checksum,
        );

        // Ensure that a packet with an identifier that isn't the bound
        // ID is not accepted
        assert!(!socket.accepts(&mut cx, &REMOTE_IPV6_REPR, &icmp_repr.into()));
    }

    #[test]
    fn test_accepts_udp() {
        let mut socket = socket(buffer(1), buffer(1));
        let mut cx = Context::mock();
        assert_eq!(socket.bind(Endpoint::Udp(LOCAL_END_V6)), Ok(()));

        let checksum = ChecksumCapabilities::default();

        let mut bytes = [0xff; 18];
        let mut packet = UdpPacket::new_unchecked(&mut bytes);
        UDP_REPR.emit(
            &mut packet,
            &REMOTE_IPV6.into(),
            &LOCAL_IPV6.into(),
            UDP_PAYLOAD.len(),
            |buf| buf.copy_from_slice(UDP_PAYLOAD),
            &checksum,
        );

        let data = &packet.into_inner()[..];

        let icmp_repr = Icmpv6Repr::DstUnreachable {
            reason: Icmpv6DstUnreachable::PortUnreachable,
            header: Ipv6Repr {
                src_addr: LOCAL_IPV6,
                dst_addr: REMOTE_IPV6,
                next_header: IpProtocol::Icmpv6,
                payload_len: 12,
                hop_limit: 0x40,
            },
            data: data,
        };
        let ip_repr = IpRepr::Unspecified {
            src_addr: REMOTE_IPV6.into(),
            dst_addr: LOCAL_IPV6.into(),
            protocol: IpProtocol::Icmpv6,
            payload_len: icmp_repr.buffer_len(),
            hop_limit: 0x40,
        };

        assert!(!socket.can_recv());

        // Ensure we can accept ICMP error response to the bound
        // UDP port
        assert!(socket.accepts(&mut cx, &ip_repr, &icmp_repr.into()));
        assert_eq!(socket.process(&mut cx, &ip_repr, &icmp_repr.into()), Ok(()));
        assert!(socket.can_recv());

        let mut bytes = [0x00; 66];
        let mut packet = Icmpv6Packet::new_unchecked(&mut bytes[..]);
        icmp_repr.emit(
            &LOCAL_IPV6.into(),
            &REMOTE_IPV6.into(),
            &mut packet,
            &checksum,
        );
        assert_eq!(
            socket.recv(),
            Ok((&packet.into_inner()[..], REMOTE_IPV6.into()))
        );
        assert!(!socket.can_recv());
    }
}