riot_coap_handler_demos/
ping_passive.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
//! A monitor resource for incoming pings.
//!
//! In difficult communication situations, especially with asymmetric communication, the ability to
//! detect whether one ping only was sent or not can make all the difference.
//!
//! ## Setup
//!
//! The resource handler is most easily used by having a static [`PingHistoryMutex`] and hooking it
//! into a CoAP handler tree.
//!
//! To receive messages through GNRC, a callback slot needs to be allocated and wired up.
//!
//! ```ignore
//! static PING_PASSIVE: PingHistoryMutex<{ DEFAULT_SIZE }> = PingHistoryMutex::new();
//!
//! let handler = coap_message_demos::full_application_tree(None)
//!     .at(&["pinged"], riot_coap_handler_demos::ping_passive::resource(&PING_PASSIVE))
//!     .with_wkc()
//!     ;
//!
//! static PASSIVE_SLOT: static_cell::StaticCell<riot_wrappers::gnrc::netreg::callback::Slot<&'static PingHistoryMutex<{ DEFAULT_SIZE }>>> =
//!     static_cell::StaticCell::new();
//! PING_PASSIVE.register(PASSIVE_SLOT.init(Default::default()));
//! ```
//!
//! ## Usage
//!
//! When registered as `/pinged`, you can run
//!
//! ```shell
//! $ aiocoap-client 'coap://[2001:db8::1]/pinged'
//! # CBOR message shown in Diagnostic Notation
//! [0]
//! ```
//!
//! and see that no pings have been received in a very rudimentary and likely to change format.
//!
//! Once you have sent a ping, you will see the change, and using different addresses shows
//! differentiated results:
//!
//! ```shell
//! $ ping fe80::3c63:beff:fe85:ca96%tapbr0 -c1
//! [...]
//! $ aiocoap-client 'coap://[2001:db8::1]/pinged'
//! [0, 54([ip'fe80::f30:40e4:6c93:e17d', null, 6])]
//! $ ping 2001:db8::3c63:beff:fe85:ca96 -c1
//! [0, 54([ip'fe80::f30:40e4:6c93:e17d', null, 6]), IP'2001:db8::1']
//! ```
//!
//! Once the list of received pings overflows, the number of discarded pings in the first place of
//! the list is incremented.
//!
//! The state of the handler can be reset using `-m DELETE`.
//!
//! ## Interface
//!
//! In CoAP resource discovery, a resource behaving like this can be recognized by the interface
//! description `if=tag:chrysn@fsfe.org,2024-09-16:pinged`. Any such resource supports the DELETE
//! operation to reset its state, and a GET with the application/cbor content format.
//!
//! The format may be extended in the future to contain items that are not IPv6 addresses with tag
//! 54. Such items may be ignored by consumers, but can be shown in diagnostic notation. Items that
//! are arrays will contain an IP address (possibly not tagged) as the first item, which may be
//! shown instead; if the array contains more than one item, the trailing items are ignored or
//! shown just like non-IP items.
//!
//! Compatible updates to this interface can happen by including items in the top or inner arrays;
//! incompatible updates will use a different interface description.

use crate::minicbor_helpers::*;

use riot_wrappers::mutex::Mutex;

use coap_handler_implementations::wkc::ConstantSingleRecordReport;
use coap_handler_implementations::TypeRenderable;

pub const DEFAULT_SIZE: usize = 4;

#[derive(Debug, Clone)]
pub struct PingHistory<const N: usize> {
    discarded: core::num::Wrapping<u32>,
    addresses: [Option<IpWithZone>; N],
}

impl<C, const N: usize> minicbor::Encode<C> for PingHistory<N> {
    fn encode<W: minicbor::encode::Write>(
        &self,
        mut e: &mut minicbor::Encoder<W>,
        _ctx: &mut C,
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let elements = self.addresses.iter().filter(|x| x.is_some()).count();
        let elements = u64::try_from(elements)
            .expect("Counts in memory will not exceed u64 for as long as CBOR is in use");
        e = e.array(1 + elements)?;
        e = e.encode(self.discarded)?;
        for a in self.addresses.iter().rev() {
            if let Some(a) = a {
                e = e.encode(a)?;
            }
        }
        Ok(())
    }
}

impl<const N: usize> PingHistory<N> {
    const fn new() -> Self {
        PingHistory {
            discarded: core::num::Wrapping(0),
            addresses: [const { None }; N],
        }
    }
}

pub struct PingHistoryMutex<const N: usize>(Mutex<PingHistory<N>>);

impl<const N: usize> PingHistoryMutex<N> {
    pub const fn new_any_size() -> Self {
        Self(Mutex::new(PingHistory::new()))
    }

    /// Set up a hook for receiving ICMP messages.
    ///
    /// It requires a 'static Self to ease GNRC registrations, and GNRC callback slot that contains
    /// the memory needed for handling the registration. Note that the slot can be crated through a
    /// `static_cell::StaticCell` initialized with `SLOT.init(Default::default())`, and by its own
    /// construction is previously unused. (The static mutable reference is consumed in this
    /// function).
    pub fn register(
        self: &'static Self,
        callback_slot: &'static mut riot_wrappers::gnrc::netreg::callback::Slot<&'static Self>,
    ) {
        riot_wrappers::gnrc::netreg::callback::register_static(
            callback_slot,
            self,
            riot_wrappers::gnrc::netreg::FullDemuxContext::new_icmpv6_echo(
                riot_wrappers::gnrc::icmpv6::EchoType::Request,
            ),
        );
    }
}

impl PingHistoryMutex<DEFAULT_SIZE> {
    pub const fn new() -> Self {
        Self(Mutex::new(PingHistory::new()))
    }
}

impl<const N: usize> riot_wrappers::gnrc::netreg::callback::Callback
    for &'static PingHistoryMutex<N>
{
    fn called(
        &self,
        cmd: riot_wrappers::gnrc::netreg::callback::Command,
        packet: riot_wrappers::gnrc_pktbuf::Pktsnip<riot_wrappers::gnrc_pktbuf::Shared>,
    ) {
        if cmd != riot_wrappers::gnrc::netreg::callback::Command::Receive {
            // We're not responsible for outgoing ping requests (but can only subscribe to both
            // kinds of events)
            return;
        }

        let sender = packet
            .ipv6_get_header()
            .expect("Recieved packet that's not IPv6")
            .src();
        let icmpv6 = packet
            .search_type(riot_sys::gnrc_nettype_t_GNRC_NETTYPE_ICMPV6)
            .expect("Received packet that's not ICMPv6");
        // FIXME: We're not really extracting anything from there yet (but could retain content for
        // some pings)
        let _ = icmpv6;

        let zone = packet
            .netif_get_header()
            // Not differentiating between "none specified" and "not coming from a netif" (and
            // can't differentiate between "none specified" and "some error in there" because
            // KernelPID just refeuses to use either)
            .and_then(|h| h.if_pid())
            .map(|pid| pid.into());

        let Some(mut history) = self.0.try_lock() else {
            // Silently discarding; we're probably in some kind of overflow/resource exhaustion
            // situation
            return;
        };

        // FIXME: A generalized scroll-ring could contain those as well, and maybe offer easier
        // streaming out
        history.addresses.rotate_right(1);
        if history.addresses[0].is_some() {
            history.discarded += 1;
        }
        history.addresses[0] = Some(IpWithZone {
            ip: sender.into(),
            zone,
        });
    }
}

// FIXME: Could be do this on PingHistory and rely on an impl for Mutex in riot-wrappers (but then
// needs to do it for all coap-handler-implementations versions)
impl<const N: usize> TypeRenderable for &'_ PingHistoryMutex<N> {
    type Get = PingHistory<N>;
    type Post = ();
    type Put = ();

    fn get(&mut self) -> Result<Self::Get, u8> {
        self.0
            .try_lock()
            // FIXME this shows a severe shortcoming of the handler: Even if we set a MutexGuard as
            // our Get type (which would otherwise be an option), Encode is not implemented on
            // that.
            .map(|d| d.clone())
            .ok_or(coap_numbers::code::SERVICE_UNAVAILABLE)
    }

    fn delete(&mut self) -> u8 {
        if let Some(mut history) = self.0.try_lock() {
            *history = PingHistory::new();
            coap_numbers::code::DELETED
        } else {
            coap_numbers::code::SERVICE_UNAVAILABLE
        }
    }
}

pub fn resource<'a, const N: usize>(
    pings: &'a PingHistoryMutex<N>,
) -> impl coap_handler::Handler + coap_handler::Reporting + 'a {
    ConstantSingleRecordReport::new(
        coap_handler_implementations::TypeHandler::new_minicbor_0_24(pings),
        &[
            coap_handler::Attribute::Title("Received ICMP pings"),
            coap_handler::Attribute::Interface("tag:chrysn@fsfe.org,2024-09-16:pinged"),
        ],
    )
}