batman-robin 1.0.1

Rust library and CLI tool for interacting with the BATMAN-adv kernel module for mesh networking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::commands::{if_indextoname, if_nametoindex};
use crate::error::RobinError;
use crate::model::{AttrValueForSend, Attribute, Command, Interface};
use crate::netlink;

use neli::consts::{
    nl::{NlmF, Nlmsg},
    rtnl::{Ifla, IflaInfo, RtAddrFamily, Rtm},
    socket::NlFamily,
};
use neli::genl::Genlmsghdr;
use neli::nl::{NlPayload, Nlmsghdr};
use neli::router::asynchronous::NlRouter;
use neli::rtnl::{Ifinfomsg, IfinfomsgBuilder, RtattrBuilder};
use neli::types::{Buffer, RtBuffer};
use neli::utils::Groups;

/// Counts the number of physical or virtual interfaces attached to a BATMAN-adv mesh interface.
///
/// # Arguments
///
/// * `mesh_if` - The name of the mesh interface (e.g., `"bat0"`).
///
/// # Returns
///
/// Returns the number of interfaces currently enslaved to the given mesh interface,
/// or a `RobinError` if the query fails.
///
/// # Example
///
/// ```no_run
/// # async fn example() {
/// # let count = 0u32;
/// // let count = count_interfaces("bat0").await?;
/// println!("Number of interfaces: {}", count);
/// # }
/// ```
pub async fn count_interfaces(mesh_if: &str) -> Result<u32, RobinError> {
    let mesh_ifindex = if_nametoindex(mesh_if).await.map_err(|_| {
        RobinError::Netlink(format!(
            "Error - interface '{}' is not present or not a batman-adv interface",
            mesh_if
        ))
    })?;

    let (rtnl, _) = NlRouter::connect(NlFamily::Route, None, Groups::empty())
        .await
        .map_err(|_| {
            RobinError::Netlink("Error - failed to connect to netlink router".to_string())
        })?;

    rtnl.enable_ext_ack(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable extended ACK".to_string()))?;
    rtnl.enable_strict_checking(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable strict checking".to_string()))?;

    let ifinfomsg = IfinfomsgBuilder::default()
        .ifi_family(RtAddrFamily::Unspecified)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build Ifinfomsg".to_string()))?;

    let mut response = rtnl
        .send::<_, _, Rtm, Ifinfomsg>(
            Rtm::Getlink,
            NlmF::DUMP | NlmF::ACK,
            NlPayload::Payload(ifinfomsg),
        )
        .await
        .map_err(|_| RobinError::Netlink("Error - failed to send Getlink request".to_string()))?;

    let mut count = 0u32;
    while let Some(msg) = response.next().await {
        let msg: Nlmsghdr<Rtm, Ifinfomsg> = msg.map_err(|_| {
            RobinError::Netlink("Error - failed to parse netlink message".to_string())
        })?;

        if let Some(payload) = msg.get_payload() {
            let attrs = payload.rtattrs().get_attr_handle();
            if let Ok(master) = attrs.get_attr_payload_as::<u32>(Ifla::Master)
                && master == mesh_ifindex
            {
                count += 1;
            }
        }
    }

    Ok(count)
}

/// Retrieves the list of interfaces associated with a BATMAN-adv mesh interface.
///
/// This corresponds to the `batctl if` command. Each entry contains the interface name
/// and whether it is currently active.
///
/// # Arguments
///
/// * `mesh_if` - The name of the mesh interface.
///
/// # Returns
///
/// Returns a vector of `Interface` structs or a `RobinError` if the query fails.
///
/// # Example
///
/// ```no_run
/// # use batman_robin::model::Interface;
/// # async fn example() {
/// # let ifaces: Vec<Interface> = vec![];
/// // let ifaces = get_interfaces("bat0").await?;
/// for iface in ifaces {
///     println!("Interface {} active: {}", iface.ifname, iface.active);
/// }
/// # }
/// ```
pub async fn get_interfaces(mesh_if: &str) -> Result<Vec<Interface>, RobinError> {
    let mut attrs = netlink::GenlAttrBuilder::new();
    let mesh_ifindex = if_nametoindex(mesh_if).await.map_err(|_| {
        RobinError::Netlink(format!(
            "Error - interface '{}' is not present or not a batman-adv interface",
            mesh_if
        ))
    })?;

    attrs
        .add(
            Attribute::BatadvAttrMeshIfindex,
            AttrValueForSend::U32(mesh_ifindex),
        )
        .map_err(|_| {
            RobinError::Netlink("Error - failed to add MeshIfindex attribute".to_string())
        })?;

    let msg = netlink::build_genl_msg(Command::BatadvCmdGetHardif, attrs.build())
        .map_err(|_| RobinError::Netlink("Error - failed to build netlink message".to_string()))?;

    let mut sock = netlink::BatadvSocket::connect().await.map_err(|_| {
        RobinError::Netlink("Error - failed to connect to batman-adv socket".to_string())
    })?;

    let mut response = sock
        .send(NlmF::REQUEST | NlmF::DUMP, msg)
        .await
        .map_err(|_| RobinError::Netlink("Error - failed to send netlink request".to_string()))?;

    let mut interfaces = Vec::new();
    while let Some(msg) = response.next().await {
        let msg: Nlmsghdr<u16, Genlmsghdr<u8, u16>> = msg.map_err(|_| {
            RobinError::Netlink("Error - failed to parse netlink message".to_string())
        })?;

        match *msg.nl_type() {
            x if x == Nlmsg::Done.into() => break,
            x if x == Nlmsg::Error.into() => {
                match &msg.nl_payload() {
                    NlPayload::Err(err) if *err.error() == 0 => break, // end of dump
                    NlPayload::Err(err) => {
                        return Err(RobinError::Netlink(format!(
                            "Netlink error {}",
                            err.error()
                        )));
                    }
                    _ => {
                        return Err(RobinError::Netlink(
                            "Unknown netlink error payload".to_string(),
                        ));
                    }
                }
            }
            _ => {}
        }

        let attrs = msg
            .get_payload()
            .ok_or_else(|| RobinError::Parse("Error - message has no payload".into()))?
            .attrs()
            .get_attr_handle();

        let hard_ifindex = attrs
            .get_attr_payload_as::<u32>(Attribute::BatadvAttrHardIfindex.into())
            .map_err(|_| RobinError::Parse("Error - missing HARD_IFINDEX".into()))?;

        let ifname = if_indextoname(hard_ifindex).await.map_err(|_| {
            RobinError::Netlink(format!(
                "Error - failed to resolve interface index {}",
                hard_ifindex
            ))
        })?;

        let active = attrs
            .get_attribute(Attribute::BatadvAttrActive.into())
            .is_some();

        interfaces.push(Interface { ifname, active });
    }

    Ok(interfaces)
}

/// Adds or removes a physical interface from a BATMAN-adv mesh interface.
///
/// This corresponds to `batctl if add` or `batctl if del`.
///
/// # Arguments
///
/// * `iface` - The name of the interface to add or remove.
/// * `mesh_if` - Optional mesh interface name to attach to. `None` removes it from any mesh.
///
/// # Returns
///
/// Returns `Ok(())` on success, or a `RobinError` if the operation fails.
///
/// # Example
///
/// ```no_run
/// # async fn example() {
/// // set_interface("eth0", Some("bat0")).await?;
/// // set_interface("eth0", None).await?; // remove from mesh
/// # }
/// ```
pub async fn set_interface(iface: &str, mesh_if: Option<&str>) -> Result<(), RobinError> {
    let iface_ifindex = if_nametoindex(iface)
        .await
        .map_err(|_| RobinError::Netlink(format!("Error - interface '{}' not found", iface)))?;

    let mut mesh_ifindex = 0;
    if let Some(mesh) = mesh_if {
        mesh_ifindex = if_nametoindex(mesh).await.map_err(|_| {
            RobinError::Netlink(format!("Error - mesh interface '{}' not found", mesh))
        })?;
    }

    let (rtnl, _) = NlRouter::connect(NlFamily::Route, None, Groups::empty())
        .await
        .map_err(|_| {
            RobinError::Netlink("Error - failed to connect to netlink router".to_string())
        })?;

    rtnl.enable_ext_ack(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable extended ACK".to_string()))?;
    rtnl.enable_strict_checking(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable strict checking".to_string()))?;

    let master_attr = RtattrBuilder::default()
        .rta_type(Ifla::Master)
        .rta_payload(mesh_ifindex)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build Master attribute".to_string()))?;

    let mut rtattrs: RtBuffer<Ifla, Buffer> = RtBuffer::new();
    rtattrs.push(master_attr);

    let msg = IfinfomsgBuilder::default()
        .ifi_family(RtAddrFamily::Unspecified)
        .ifi_index(iface_ifindex.cast_signed())
        .rtattrs(rtattrs)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build Ifinfomsg".to_string()))?;

    rtnl.send::<_, _, Rtm, Ifinfomsg>(
        Rtm::Setlink,
        NlmF::REQUEST | NlmF::ACK,
        NlPayload::Payload(msg),
    )
    .await
    .map_err(|_| RobinError::Netlink("Error - failed to set interface".to_string()))?;

    Ok(())
}

/// Creates a new BATMAN-adv mesh interface.
///
/// Optionally, a routing algorithm can be specified. This corresponds to `ip link add type batadv`.
///
/// # Arguments
///
/// * `mesh_if` - The name of the mesh interface to create.
/// * `routing_algo` - Optional routing algorithm name (e.g., `"BATMAN_IV"`).
///
/// # Returns
///
/// Returns `Ok(())` on success, or a `RobinError` if creation fails.
///
/// # Example
///
/// ```no_run
/// # async fn example() {
/// // create_interface("bat0", Some("BATMAN_IV")).await?;
/// # }
/// ```
pub async fn create_interface(mesh_if: &str, routing_algo: Option<&str>) -> Result<(), RobinError> {
    const IFLA_BATADV_ALGO_NAME: u16 = 1;
    let (rtnl, _) = NlRouter::connect(NlFamily::Route, None, Groups::empty())
        .await
        .map_err(|_| {
            RobinError::Netlink("Error - failed to connect to netlink router".to_string())
        })?;

    rtnl.enable_ext_ack(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable extended ACK".to_string()))?;
    rtnl.enable_strict_checking(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable strict checking".to_string()))?;

    let ifname_attr = RtattrBuilder::default()
        .rta_type(Ifla::Ifname)
        .rta_payload(mesh_if)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build IFNAME attribute".to_string()))?;

    let kind_attr = RtattrBuilder::default()
        .rta_type(IflaInfo::Kind)
        .rta_payload("batadv")
        .build()
        .map_err(|_| {
            RobinError::Netlink("Error - failed to build INFO_KIND attribute".to_string())
        })?;

    let mut info_data_attrs: RtBuffer<u16, Buffer> = RtBuffer::new();
    if let Some(algo) = routing_algo {
        let algo_attr = RtattrBuilder::default()
            .rta_type(IFLA_BATADV_ALGO_NAME)
            .rta_payload(algo)
            .build()
            .map_err(|_| {
                RobinError::Netlink("Error - failed to build ALGO_NAME attribute".to_string())
            })?;
        info_data_attrs.push(algo_attr);
    }

    let info_data_attr = RtattrBuilder::default()
        .rta_type(IflaInfo::Data)
        .rta_payload(info_data_attrs)
        .build()
        .map_err(|_| {
            RobinError::Netlink("Error - failed to build INFO_DATA attribute".to_string())
        })?;

    let mut linkinfo_attrs: RtBuffer<IflaInfo, Buffer> = RtBuffer::new();
    linkinfo_attrs.push(kind_attr);
    linkinfo_attrs.push(info_data_attr);

    let linkinfo_attr = RtattrBuilder::default()
        .rta_type(Ifla::Linkinfo)
        .rta_payload(linkinfo_attrs)
        .build()
        .map_err(|_| {
            RobinError::Netlink("Error - failed to build LINKINFO attribute".to_string())
        })?;

    let mut rtattrs: RtBuffer<Ifla, Buffer> = RtBuffer::new();
    rtattrs.push(ifname_attr);
    rtattrs.push(linkinfo_attr);

    let msg = IfinfomsgBuilder::default()
        .ifi_family(RtAddrFamily::Unspecified)
        .rtattrs(rtattrs)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build Ifinfomsg".to_string()))?;

    rtnl.send::<_, _, Rtm, Ifinfomsg>(
        Rtm::Newlink,
        NlmF::REQUEST | NlmF::CREATE | NlmF::EXCL | NlmF::ACK,
        NlPayload::Payload(msg),
    )
    .await
    .map_err(|_| RobinError::Netlink("Error - failed to create mesh interface".to_string()))?;

    Ok(())
}

/// Destroys an existing BATMAN-adv mesh interface.
///
/// This corresponds to `ip link delete <mesh_if>`.
///
/// # Arguments
///
/// * `mesh_if` - The name of the mesh interface to destroy.
///
/// # Returns
///
/// Returns `Ok(())` on success, or a `RobinError` if destruction fails.
///
/// # Example
///
/// ```no_run
/// # async fn example() {
/// // destroy_interface("bat0").await?;
/// # }
/// ```
pub async fn destroy_interface(mesh_if: &str) -> Result<(), RobinError> {
    let (rtnl, _) = NlRouter::connect(NlFamily::Route, None, Groups::empty())
        .await
        .map_err(|_| {
            RobinError::Netlink("Error - failed to connect to netlink router".to_string())
        })?;

    rtnl.enable_ext_ack(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable extended ACK".to_string()))?;
    rtnl.enable_strict_checking(true)
        .map_err(|_| RobinError::Netlink("Error - failed to enable strict checking".to_string()))?;

    let ifname_attr = RtattrBuilder::default()
        .rta_type(Ifla::Ifname)
        .rta_payload(mesh_if)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build IFNAME attribute".to_string()))?;

    let mut rtattrs: RtBuffer<Ifla, Buffer> = RtBuffer::new();
    rtattrs.push(ifname_attr);

    let msg = IfinfomsgBuilder::default()
        .ifi_family(RtAddrFamily::Unspecified)
        .rtattrs(rtattrs)
        .build()
        .map_err(|_| RobinError::Netlink("Error - failed to build Ifinfomsg".to_string()))?;

    rtnl.send::<_, _, Rtm, Ifinfomsg>(
        Rtm::Dellink,
        NlmF::REQUEST | NlmF::ACK,
        NlPayload::Payload(msg),
    )
    .await
    .map_err(|_| RobinError::Netlink("Error - failed to destroy mesh interface".to_string()))?;

    Ok(())
}