netlink_wi 0.8.0

A library to retrieve information about wireless hardware in Linux operating system using netlink protocol.
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
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
use std::collections::HashMap;
use std::fmt::Write;
use std::io::Cursor;

use log::debug;
use neli::consts::nl::Nlmsg;
use neli::consts::socket::NlFamily;
use neli::err::RouterError;
use neli::nl::NlPayload;
use neli::router::asynchronous::{NlRouter, NlRouterReceiverHandle};
use neli::utils::Groups;
use neli::ToBytes;

use crate::attributes::{Attribute, Attrs, MonitorFlags};
use crate::error::Result;
use crate::interface::InterfaceType;
use crate::netlink::{ChannelConfig, Neli80211Header, Nl80211Request};
use crate::reg_domain::RegulatoryDomain;
use crate::station::WirelessStation;
use crate::wiphy::PhysicalDevice;

use super::interface::WirelessInterface;

/// An asynchronous netlink socket for interacting with nl80211.
///
/// This socket provides an async interface to nl80211 (the Linux kernel's 802.11
/// wireless configuration API). It allows you to query and configure wireless
/// interfaces, physical devices, stations, and regulatory domains.
///
/// # Examples
///
/// ```no_run
/// # use netlink_wi::AsyncNlSocket;
/// # async fn example() -> netlink_wi::NlResult<()> {
/// let socket = AsyncNlSocket::connect().await?;
/// let interfaces = socket.list_interfaces().await?;
/// # Ok(())
/// # }
/// ```
pub struct AsyncNlSocket {
    socket: NlRouter,
    nl_type: u16,
}

impl AsyncNlSocket {
    /// Connects to the nl80211 netlink socket.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The netlink socket connection fails
    /// - The nl80211 family cannot be resolved
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect() -> Result<Self> {
        let (socket, _) = NlRouter::connect(NlFamily::Generic, None, Groups::empty()).await?;
        let nl_type = socket.resolve_genl_family("nl80211").await?;
        Ok(Self { socket, nl_type })
    }

    /// Lists all wireless network interfaces currently available on the system.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// let interfaces = socket.list_interfaces().await?;
    /// for interface in interfaces {
    ///     println!("Interface: {}", interface.interface_index);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_interfaces(&self) -> Result<Vec<WirelessInterface>> {
        let request = Nl80211Request::list_interfaces();
        let recv = self.send(request).await?;
        let mut responses = Vec::new();
        Self::handle_dump_response(recv, |handle| {
            responses.push(TryInto::<WirelessInterface>::try_into(handle)?);
            Ok(())
        })
        .await?;
        Ok(responses)
    }

    /// Retrieves information about the wireless interface with the specified interface index.
    ///
    /// # Arguments
    ///
    /// * `if_index` - The interface index to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// if let Some(interface) = socket.get_interface(3).await? {
    ///     println!("Found interface: {}", interface.interface_index);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_interface(&self, if_index: u32) -> Result<Option<WirelessInterface>> {
        let request = Nl80211Request::get_interface(if_index);
        let recv = self.send(request).await?;

        let mut result: Option<WirelessInterface> = None;
        Self::handle_dump_response(recv, |handle| {
            let device: WirelessInterface = handle.try_into()?;
            if device.interface_index == if_index {
                result = Some(device);
            }
            Ok(())
        })
        .await?;
        Ok(result)
    }

    /// Sets the type of a wireless interface.
    ///
    /// Changes the operating mode of the specified wireless interface
    /// (e.g., station, access point, monitor mode).
    ///
    /// # Arguments
    ///
    /// * `if_index` - The interface index to modify
    /// * `if_type` - The new interface type to set
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # use netlink_wi::interface::InterfaceType;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// socket.set_interface(3, InterfaceType::Monitor).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_interface(&self, if_index: u32, if_type: InterfaceType) -> Result<()> {
        let request = Nl80211Request::set_interface(if_index, if_type);
        let recv = self.send(request).await?;
        Self::handle_ack_response(recv).await
    }

    /// Configures the monitor mode flags for an interface in monitor mode.
    ///
    /// # Arguments
    ///
    /// * `if_index` - The interface index to modify
    /// * `flags` - A vector of monitor flags to set
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::{AsyncNlSocket, MonitorFlags};
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// let flags = vec![MonitorFlags::FcsFail, MonitorFlags::Control];
    /// socket.set_monitor_flags(3, flags).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_monitor_flags(&self, if_index: u32, flags: Vec<MonitorFlags>) -> Result<()> {
        let request = Nl80211Request::set_monitor_flags(if_index, flags);
        let recv = self.send(request).await?;
        Self::handle_ack_response(recv).await
    }

    /// Sets the channel configuration for a wireless interface.
    ///
    /// # Arguments
    ///
    /// * `config` - The channel configuration to apply
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::{AsyncNlSocket, ChannelConfig};
    /// # use netlink_wi::interface::ChannelWidth;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// let config = ChannelConfig::new(
    ///     3, // interface index
    ///     2437, // Channel 6
    ///     ChannelWidth::Width20,
    /// );
    /// socket.set_channel(config).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_channel(&self, config: ChannelConfig) -> Result<()> {
        let request = Nl80211Request::set_channel(config);
        let recv = self.send(request).await?;
        Self::handle_ack_response(recv).await
    }

    /// Lists all wireless stations associated with an interface.
    ///
    /// Retrieves information about all stations (clients) currently associated
    /// with the specified wireless interface.
    ///
    /// # Arguments
    ///
    /// * `if_index` - The interface index to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// let stations = socket.list_stations(3).await?;
    /// for station in stations {
    ///     println!("Station MAC: {:?}", station.mac);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_stations(&self, if_index: u32) -> Result<Vec<WirelessStation>> {
        let request = Nl80211Request::list_stations(if_index);
        let recv = self.send(request).await?;

        let mut responses = Vec::new();
        Self::handle_dump_response(recv, |handle| {
            responses.push(TryInto::<WirelessStation>::try_into(handle)?);
            Ok(())
        })
        .await?;
        Ok(responses)
    }

    /// Lists all physical wireless devices (wiphys).
    ///
    /// Retrieves information about all physical wireless devices (PHYs) available
    /// on the system. Each physical device may have multiple virtual interfaces.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// let devices = socket.list_physical_devices().await?;
    /// for device in devices {
    ///     println!("PHY index: {}", device.wiphy_index);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_physical_devices(&self) -> Result<Vec<PhysicalDevice>> {
        let request = Nl80211Request::list_physical_devices();
        let recv = self.send(request).await?;

        let mut responses = HashMap::new();
        Self::handle_dump_response(recv, |handle| {
            let device: PhysicalDevice = handle.try_into()?;
            responses
                .entry(device.wiphy_index)
                .and_modify(|d: &mut PhysicalDevice| d.merge(&device))
                .or_insert(device);
            Ok(())
        })
        .await?;
        Ok(responses.values().cloned().collect())
    }

    /// Retrieves detailed information about the physical wireless device (PHY)
    /// with the specified wiphy index.
    ///
    /// # Arguments
    ///
    /// * `wiphy_index` - The wiphy index to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// if let Some(device) = socket.get_physical_device(0).await? {
    ///     println!("PHY: {}", device.wiphy_index);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_physical_device(&self, wiphy_index: u32) -> Result<Option<PhysicalDevice>> {
        let request = Nl80211Request::get_physical_device(wiphy_index);
        let recv = self.send(request).await?;

        let mut result: Option<PhysicalDevice> = None;
        Self::handle_dump_response(recv, |handle| {
            let device: PhysicalDevice = handle.try_into()?;
            if device.wiphy_index == wiphy_index {
                if let Some(d) = result.as_mut() {
                    d.merge(&device);
                } else {
                    result = Some(device);
                }
            }
            Ok(())
        })
        .await?;
        Ok(result)
    }

    /// Retrieves information about the current wireless regulatory domain,
    /// which defines the allowed frequencies, power limits, and other
    /// regulatory restrictions for wireless operation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// let domains = socket.get_regulatory_domain().await?;
    /// for domain in domains {
    ///     println!("Regulatory domain: {:?}", domain);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_regulatory_domain(&self) -> Result<Vec<RegulatoryDomain>> {
        let request = Nl80211Request::get_regulatory_domain();
        let recv = self.send(request).await?;

        let mut responses = Vec::new();
        Self::handle_dump_response(recv, |handle| {
            responses.push(TryInto::<RegulatoryDomain>::try_into(handle)?);
            Ok(())
        })
        .await?;
        Ok(responses)
    }

    /// Triggers a wireless scan on the specified interface.
    ///
    /// # Arguments
    ///
    /// * `if_index` - The interface index to scan with
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// socket.trigger_scan(3).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn trigger_scan(&self, if_index: u32) -> Result<()> {
        let request = Nl80211Request::trigger_scan(if_index);
        let recv = self.send(request).await?;
        Self::handle_ack_response(recv).await
    }

    /// Aborts an ongoing wireless scan on the specified interface.
    ///
    /// # Arguments
    ///
    /// * `if_index` - The interface index to abort the scan on
    ///
    /// # Errors
    ///
    /// Returns NlError ENOENT if a scan is not running.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use netlink_wi::AsyncNlSocket;
    /// # async fn example() -> netlink_wi::NlResult<()> {
    /// let socket = AsyncNlSocket::connect().await?;
    /// socket.trigger_scan(3).await?;
    /// // some time later
    /// socket.abort_scan(3).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn abort_scan(&self, if_index: u32) -> Result<()> {
        let request = Nl80211Request::abort_scan(if_index);
        let recv = self.send(request).await?;
        Self::handle_ack_response(recv).await
    }

    async fn send(
        &self,
        request: Nl80211Request,
    ) -> std::result::Result<
        NlRouterReceiverHandle<Nlmsg, Neli80211Header>,
        RouterError<u16, Neli80211Header>,
    > {
        if cfg!(debug_assertions) {
            let mut b: Cursor<Vec<u8>> = Cursor::new(Vec::new());
            request.nl_payload.to_bytes(&mut b).unwrap();
            let octets: String = b.get_ref().iter().fold(String::new(), |mut output, b| {
                let _ = write!(output, "{b:02x} ");
                output
            });
            debug!("[PAYLOAD] {octets}");
        }
        self.socket
            .send(self.nl_type, request.nl_flags, request.nl_payload)
            .await
    }

    async fn handle_dump_response<F: FnMut(&Attrs<'_, Attribute>) -> Result<()>>(
        mut recv: NlRouterReceiverHandle<Nlmsg, Neli80211Header>,
        mut f: F,
    ) -> Result<()> {
        while let Some(Ok(response)) = recv.next::<Nlmsg, Neli80211Header>().await {
            match response.nl_payload() {
                NlPayload::Err(err) => {
                    debug!("Error when reading dump response: {err}");
                    return Err(err.clone().into());
                }
                NlPayload::Payload(payload) => {
                    let handle = payload.attrs().get_attr_handle();
                    f(&handle)?
                }
                NlPayload::Empty | NlPayload::Ack(_) | NlPayload::DumpExtAck(_) => (),
            };
        }
        Ok(())
    }

    async fn handle_ack_response(
        mut recv: NlRouterReceiverHandle<Nlmsg, Neli80211Header>,
    ) -> Result<()> {
        while let Some(response) = recv.next::<Nlmsg, Neli80211Header>().await {
            let response = response?;
            match response.nl_payload() {
                NlPayload::Err(err) => {
                    debug!("Error when reading ack response: {err}");
                    return Err(err.clone().into());
                }
                NlPayload::Payload(_)
                | NlPayload::Empty
                | NlPayload::Ack(_)
                | NlPayload::DumpExtAck(_) => (),
            };
        }
        Ok(())
    }
}