openthread/ot/
ip6.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
// Copyright 2021 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.

use crate::prelude_internal::*;

/// Functional equivalent of [`otsys::otIcmp6EchoMode`](crate::otsys::otIcmp6EchoMode).
#[derive(Debug, Copy, Clone, Eq, Ord, PartialOrd, PartialEq, num_derive::FromPrimitive)]
pub enum Icmp6EchoMode {
    /// ICMPv6 Echo processing enabled for unicast and multicast requests.
    HandleAll = OT_ICMP6_ECHO_HANDLER_ALL as isize,

    /// ICMPv6 Echo processing disabled.
    HandleDisabled = OT_ICMP6_ECHO_HANDLER_DISABLED as isize,

    /// ICMPv6 Echo processing enabled only for multicast requests only.
    HandleMulticastOnly = OT_ICMP6_ECHO_HANDLER_MULTICAST_ONLY as isize,

    /// ICMPv6 Echo processing enabled only for unicast requests only.
    HandleUnicastOnly = OT_ICMP6_ECHO_HANDLER_UNICAST_ONLY as isize,
}

impl From<otIcmp6EchoMode> for Icmp6EchoMode {
    fn from(x: otIcmp6EchoMode) -> Self {
        use num::FromPrimitive;
        Self::from_u32(x).unwrap_or_else(|| panic!("Unknown otIcmp6EchoMode value: {x}"))
    }
}

impl From<Icmp6EchoMode> for otIcmp6EchoMode {
    fn from(x: Icmp6EchoMode) -> Self {
        x as otIcmp6EchoMode
    }
}

/// Iterates over the [`NetifAddress`] structs from [`Ip6::ip6_get_unicast_addresses()`].
#[derive(Default, Debug, Clone)]
pub struct NetifAddressIterator<'a>(Option<&'a NetifAddress>);

impl<'a> Iterator for NetifAddressIterator<'a> {
    type Item = &'a NetifAddress;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(addr_ref) = self.0 {
            // SAFETY: The `otNetifAddress` pointer used here comes
            //         from `otIp6GetUnicastAddresses`, which is guaranteed
            //         to have valid values for `mNext`.
            self.0 = unsafe { NetifAddress::ref_from_ot_ptr(addr_ref.0.mNext) };
            Some(addr_ref)
        } else {
            None
        }
    }
}

/// Methods from the [OpenThread "IPv6" Module](https://openthread.io/reference/group/api-ip6).
pub trait Ip6 {
    /// Functional equivalent of [`otsys::otIp6Send`](crate::otsys::otIp6Send).
    fn ip6_send(&self, message: OtMessageBox<'_>) -> Result;

    /// Similar to [`ip6_send()`], but takes a byte slice instead
    /// of an [`OtMessageBox`](crate::OtMessageBox).
    fn ip6_send_data(&self, data: &[u8]) -> Result;

    /// Similar to [`ip6_send_data()`], but sends the packet without layer-2 security.
    fn ip6_send_data_direct(&self, data: &[u8]) -> Result;

    /// Functional equivalent of [`otsys::otIp6IsEnabled`](crate::otsys::otIp6IsEnabled).
    fn ip6_is_enabled(&self) -> bool;

    /// Functional equivalent of [`otsys::otIp6SetEnabled`](crate::otsys::otIp6SetEnabled).
    fn ip6_set_enabled(&self, enabled: bool) -> Result;

    /// Functional equivalent of
    /// [`otsys::otIp6AddUnicastAddress`](crate::otsys::otIp6AddUnicastAddress).
    fn ip6_add_unicast_address(&self, addr: &NetifAddress) -> Result;

    /// Functional equivalent of
    /// [`otsys::otIp6RemoveUnicastAddress`](crate::otsys::otIp6RemoveUnicastAddress).
    fn ip6_remove_unicast_address(&self, addr: &Ip6Address) -> Result;

    /// Functional equivalent of
    /// [`otsys::otIp6SubscribeMulticastAddress`](crate::otsys::otIp6SubscribeMulticastAddress).
    fn ip6_join_multicast_group(&self, addr: &Ip6Address) -> Result;

    /// Functional equivalent of
    /// [`otsys::otIp6UnsubscribeMulticastAddress`](crate::otsys::otIp6UnsubscribeMulticastAddress).
    fn ip6_leave_multicast_group(&self, addr: &Ip6Address) -> Result;

    /// Sets the IPv6 receive callback closure. Functional equivalent of
    /// [`otsys::otIp6SetReceiveCallback`](crate::otsys::otIp6SetReceiveCallback).
    ///
    /// The closure will ultimately be executed via
    /// [`ot::Tasklets::process`](crate::ot::Tasklets::process).
    fn ip6_set_receive_fn<'a, F>(&'a self, f: Option<F>)
    where
        F: FnMut(OtMessageBox<'_>) + 'a;

    /// Sets the IPv6 address callback closure. Functional equivalent of
    /// [`otsys::otIp6SetAddressCallback`](crate::otsys::otIp6SetAddressCallback).
    ///
    /// The closure takes two arguments:
    ///
    ///  * An instance of [`ot::Ip6AddressInfo`](crate::ot::Ip6AddressInfo).
    ///  * A `bool` indicating if the address is being added (`true`) or removed (`false`).
    ///
    /// The closure will ultimately be executed via
    /// [`ot::Tasklets::process`](crate::ot::Tasklets::process).
    fn ip6_set_address_fn<'a, F>(&'a self, f: Option<F>)
    where
        F: for<'r> FnMut(Ip6AddressInfo<'r>, bool) + 'a;

    /// Functional equivalent of [`otsys::otIp6IsSlaacEnabled`](crate::otsys::otIp6IsSlaacEnabled).
    fn ip6_is_slaac_enabled(&self) -> bool;

    /// Functional equivalent of
    /// [`otsys::otIp6SetSlaacEnabled`](crate::otsys::otIp6SetSlaacEnabled).
    fn ip6_set_slaac_enabled(&self, enabled: bool);

    /// Functional equivalent of
    /// [`otsys::otIcmp6GetEchoMode`](crate::otsys::otIcmp6GetEchoMode).
    fn icmp6_get_echo_mode(&self) -> Icmp6EchoMode;

    /// Functional equivalent of
    /// [`otsys::otIcmp6SetEchoMode`](crate::otsys::otIcmp6SetEchoMode).
    fn icmp6_set_echo_mode(&self, mode: Icmp6EchoMode);

    /// Functional equivalent of
    /// [`otsys::otIp6SetReceiveFilterEnabled`](crate::otsys::otIp6SetReceiveFilterEnabled).
    fn ip6_set_receive_filter_enabled(&self, enabled: bool);

    /// Functional equivalent of
    /// [`otsys::otIp6IsReceiveFilterEnabled`](crate::otsys::otIp6IsReceiveFilterEnabled).
    fn ip6_is_receive_filter_enabled(&self) -> bool;

    /// Functional equivalent of
    /// [`otsys::otIp6GetBorderRoutingCounters`](crate::otsys::otIp6GetBorderRoutingCounters).
    fn ip6_get_border_routing_counters(&self) -> &BorderRoutingCounters;

    /// Functional equivalent of
    /// [`otsys::otIp6GetUnicastAddresses`](crate::otsys::otIp6GetUnicastAddresses).
    fn ip6_get_unicast_addresses(&self) -> NetifAddressIterator<'_>;
}

impl<T: Ip6 + ot::Boxable> Ip6 for ot::Box<T> {
    fn ip6_send(&self, message: OtMessageBox<'_>) -> Result<()> {
        self.as_ref().ip6_send(message)
    }

    fn ip6_send_data(&self, data: &[u8]) -> Result {
        self.as_ref().ip6_send_data(data)
    }

    fn ip6_send_data_direct(&self, data: &[u8]) -> Result {
        self.as_ref().ip6_send_data_direct(data)
    }

    fn ip6_is_enabled(&self) -> bool {
        self.as_ref().ip6_is_enabled()
    }

    fn ip6_set_enabled(&self, enabled: bool) -> Result {
        self.as_ref().ip6_set_enabled(enabled)
    }

    fn ip6_add_unicast_address(&self, addr: &NetifAddress) -> Result {
        self.as_ref().ip6_add_unicast_address(addr)
    }

    fn ip6_remove_unicast_address(&self, addr: &std::net::Ipv6Addr) -> Result {
        self.as_ref().ip6_remove_unicast_address(addr)
    }

    fn ip6_join_multicast_group(&self, addr: &std::net::Ipv6Addr) -> Result {
        self.as_ref().ip6_join_multicast_group(addr)
    }

    fn ip6_leave_multicast_group(&self, addr: &std::net::Ipv6Addr) -> Result {
        self.as_ref().ip6_join_multicast_group(addr)
    }

    fn ip6_set_receive_fn<'a, F>(&'a self, f: Option<F>)
    where
        F: FnMut(OtMessageBox<'_>) + 'a,
    {
        self.as_ref().ip6_set_receive_fn(f)
    }

    fn ip6_set_address_fn<'a, F>(&'a self, f: Option<F>)
    where
        F: for<'r> FnMut(Ip6AddressInfo<'r>, bool) + 'a,
    {
        self.as_ref().ip6_set_address_fn(f)
    }

    fn ip6_is_slaac_enabled(&self) -> bool {
        self.as_ref().ip6_is_slaac_enabled()
    }

    fn ip6_set_slaac_enabled(&self, enabled: bool) {
        self.as_ref().ip6_set_slaac_enabled(enabled);
    }

    fn icmp6_get_echo_mode(&self) -> Icmp6EchoMode {
        self.as_ref().icmp6_get_echo_mode()
    }

    fn icmp6_set_echo_mode(&self, mode: Icmp6EchoMode) {
        self.as_ref().icmp6_set_echo_mode(mode)
    }

    fn ip6_set_receive_filter_enabled(&self, enabled: bool) {
        self.as_ref().ip6_set_receive_filter_enabled(enabled);
    }

    fn ip6_is_receive_filter_enabled(&self) -> bool {
        self.as_ref().ip6_is_receive_filter_enabled()
    }

    fn ip6_get_border_routing_counters(&self) -> &BorderRoutingCounters {
        self.as_ref().ip6_get_border_routing_counters()
    }

    fn ip6_get_unicast_addresses(&self) -> NetifAddressIterator<'_> {
        self.as_ref().ip6_get_unicast_addresses()
    }
}

impl Ip6 for Instance {
    fn ip6_send(&self, message: OtMessageBox<'_>) -> Result {
        Error::from(unsafe { otIp6Send(self.as_ot_ptr(), message.take_ot_ptr()) }).into()
    }

    fn ip6_send_data(&self, data: &[u8]) -> Result {
        if let Ok(msg) = Message::ip6_new_from_bytes(self, data, None) {
            self.ip6_send(msg)
        } else if self.get_buffer_info().0.mFreeBuffers == 0 {
            Err(ot::Error::NoBufs)
        } else {
            Err(ot::Error::Failed)
        }
    }

    fn ip6_send_data_direct(&self, data: &[u8]) -> Result {
        if let Ok(mut msg) = Message::ip6_new_from_bytes(self, data, None) {
            msg.set_direct_transmission(true);
            self.ip6_send(msg)
        } else if self.get_buffer_info().0.mFreeBuffers == 0 {
            Err(ot::Error::NoBufs)
        } else {
            Err(ot::Error::Failed)
        }
    }

    fn ip6_is_enabled(&self) -> bool {
        unsafe { otIp6IsEnabled(self.as_ot_ptr()) }
    }

    fn ip6_set_enabled(&self, enabled: bool) -> Result {
        Error::from(unsafe { otIp6SetEnabled(self.as_ot_ptr(), enabled) }).into()
    }

    fn ip6_add_unicast_address(&self, addr: &NetifAddress) -> Result {
        Error::from(unsafe { otIp6AddUnicastAddress(self.as_ot_ptr(), addr.as_ot_ptr()) }).into()
    }

    fn ip6_remove_unicast_address(&self, addr: &std::net::Ipv6Addr) -> Result {
        Error::from(unsafe { otIp6RemoveUnicastAddress(self.as_ot_ptr(), addr.as_ot_ptr()) }).into()
    }

    fn ip6_join_multicast_group(&self, addr: &std::net::Ipv6Addr) -> Result {
        Error::from(unsafe { otIp6SubscribeMulticastAddress(self.as_ot_ptr(), addr.as_ot_ptr()) })
            .into()
    }

    fn ip6_leave_multicast_group(&self, addr: &std::net::Ipv6Addr) -> Result {
        Error::from(unsafe { otIp6UnsubscribeMulticastAddress(self.as_ot_ptr(), addr.as_ot_ptr()) })
            .into()
    }

    fn ip6_set_receive_fn<'a, F>(&'a self, f: Option<F>)
    where
        F: FnMut(OtMessageBox<'_>) + 'a,
    {
        unsafe extern "C" fn _ot_ip6_receive_callback<'a, F: FnMut(OtMessageBox<'_>) + 'a>(
            message: *mut otMessage,
            context: *mut ::std::os::raw::c_void,
        ) {
            trace!("_ot_ip6_receive_callback");

            // Convert the `*otMessage` into an `ot::Box<ot::Message>`.
            let message = OtMessageBox::from_ot_ptr(message)
                .expect("_ot_ip6_receive_callback: Got NULL otMessage");

            // Reconstitute a reference to our closure.
            let sender = &mut *(context as *mut F);

            sender(message)
        }

        let (fn_ptr, fn_box, cb): (_, _, otIp6ReceiveCallback) = if let Some(f) = f {
            let mut x = Box::new(f);

            (
                x.as_mut() as *mut F as *mut ::std::os::raw::c_void,
                Some(x as Box<dyn FnMut(OtMessageBox<'_>) + 'a>),
                Some(_ot_ip6_receive_callback::<F>),
            )
        } else {
            (std::ptr::null_mut() as *mut ::std::os::raw::c_void, None, None)
        };

        unsafe {
            otIp6SetReceiveCallback(self.as_ot_ptr(), cb, fn_ptr);

            // Make sure our object eventually gets cleaned up.
            // Here we must also transmute our closure to have a 'static lifetime.
            // We need to do this because the borrow checker cannot infer the
            // proper lifetime for the singleton instance backing, but
            // this is guaranteed by the API.
            self.borrow_backing().ip6_receive_fn.set(std::mem::transmute::<
                Option<Box<dyn FnMut(OtMessageBox<'_>) + 'a>>,
                Option<Box<dyn FnMut(OtMessageBox<'_>) + 'static>>,
            >(fn_box));
        }
    }

    fn ip6_set_address_fn<'a, F>(&'a self, f: Option<F>)
    where
        F: for<'r> FnMut(Ip6AddressInfo<'r>, bool) + 'a,
    {
        unsafe extern "C" fn _ot_ip6_address_callback<
            'a,
            F: FnMut(Ip6AddressInfo<'_>, bool) + 'a,
        >(
            info: *const otIp6AddressInfo,
            is_added: bool,
            context: *mut ::std::os::raw::c_void,
        ) {
            trace!("_ot_ip6_address_callback");

            // Convert the `*otIp6AddressInfo` into an `&ot::Ip6AddressInfo`.
            let info = *Ip6AddressInfo::ref_from_ot_ptr(info).unwrap();

            // Reconstitute a reference to our closure.
            let sender = &mut *(context as *mut F);

            sender(info, is_added)
        }

        let (fn_ptr, fn_box, cb): (_, _, otIp6AddressCallback) = if let Some(f) = f {
            let mut x = Box::new(f);

            (
                x.as_mut() as *mut F as *mut ::std::os::raw::c_void,
                Some(x as Box<dyn FnMut(Ip6AddressInfo<'_>, bool) + 'a>),
                Some(_ot_ip6_address_callback::<F>),
            )
        } else {
            (std::ptr::null_mut() as *mut ::std::os::raw::c_void, None, None)
        };

        unsafe {
            otIp6SetAddressCallback(self.as_ot_ptr(), cb, fn_ptr);

            // Make sure our object eventually gets cleaned up.
            // Here we must also transmute our closure to have a 'static lifetime.
            // We need to do this because the borrow checker cannot infer the
            // proper lifetime for the singleton instance backing, but
            // this is guaranteed by the API.
            self.borrow_backing().ip6_address_fn.set(std::mem::transmute::<
                Option<Box<dyn FnMut(Ip6AddressInfo<'_>, bool) + 'a>>,
                Option<Box<dyn FnMut(Ip6AddressInfo<'_>, bool) + 'static>>,
            >(fn_box));
        }
    }

    fn ip6_is_slaac_enabled(&self) -> bool {
        unsafe { otIp6IsSlaacEnabled(self.as_ot_ptr()) }
    }

    fn ip6_set_slaac_enabled(&self, enabled: bool) {
        unsafe { otIp6SetSlaacEnabled(self.as_ot_ptr(), enabled) }
    }

    fn icmp6_get_echo_mode(&self) -> Icmp6EchoMode {
        unsafe { otIcmp6GetEchoMode(self.as_ot_ptr()) }.into()
    }

    fn icmp6_set_echo_mode(&self, mode: Icmp6EchoMode) {
        unsafe { otIcmp6SetEchoMode(self.as_ot_ptr(), mode.into()) }
    }

    fn ip6_set_receive_filter_enabled(&self, enabled: bool) {
        unsafe { otIp6SetReceiveFilterEnabled(self.as_ot_ptr(), enabled) }
    }

    fn ip6_is_receive_filter_enabled(&self) -> bool {
        unsafe { otIp6IsReceiveFilterEnabled(self.as_ot_ptr()) }
    }

    fn ip6_get_border_routing_counters(&self) -> &BorderRoutingCounters {
        unsafe {
            BorderRoutingCounters::ref_from_ot_ptr(otIp6GetBorderRoutingCounters(self.as_ot_ptr()))
                .unwrap()
        }
    }

    fn ip6_get_unicast_addresses(&self) -> NetifAddressIterator<'_> {
        NetifAddressIterator(unsafe {
            NetifAddress::ref_from_ot_ptr(otIp6GetUnicastAddresses(self.as_ot_ptr()))
        })
    }
}