1#![allow(unsafe_code)]
2
3use crate::backend::io::syscalls::ioctl;
4use crate::fd::AsFd;
5use crate::io;
6use core::{slice, str};
7use linux_raw_sys::ctypes::c_char;
8use linux_raw_sys::ioctl::SIOCGIFINDEX;
9#[cfg(feature = "alloc")]
10use linux_raw_sys::ioctl::SIOCGIFNAME;
11use linux_raw_sys::net::{ifreq, ifreq__bindgen_ty_1, ifreq__bindgen_ty_2, IFNAMSIZ};
12#[cfg(feature = "alloc")]
13use {alloc::borrow::ToOwned, alloc::string::String};
14
15pub(crate) fn name_to_index(fd: impl AsFd, if_name: &str) -> io::Result<u32> {
16 let if_name_bytes: &[u8] = if_name.as_bytes();
17 if if_name_bytes.len() >= IFNAMSIZ as usize {
18 return Err(io::Errno::NODEV);
19 }
20 if if_name_bytes.contains(&0) {
21 return Err(io::Errno::NODEV);
22 }
23
24 // SAFETY: Convert `&[u8]` to `&[c_char]`.
25 let if_name_bytes: &[i8] = unsafe {
26 slice::from_raw_parts(data:if_name_bytes.as_ptr().cast::<c_char>(), if_name_bytes.len())
27 };
28
29 let mut ifreq: ifreq = ifreq {
30 ifr_ifrn: ifreq__bindgen_ty_1 { ifrn_name: [0; 16] },
31 ifr_ifru: ifreq__bindgen_ty_2 { ifru_ivalue: 0 },
32 };
33 unsafe { ifreq.ifr_ifrn.ifrn_name[..if_name_bytes.len()].copy_from_slice(src:if_name_bytes) };
34
35 unsafe { ioctl(fd.as_fd(), SIOCGIFINDEX, &mut ifreq as *mut ifreq as _) }?;
36 let index: i32 = unsafe { ifreq.ifr_ifru.ifru_ivalue };
37 Ok(index as u32)
38}
39
40#[cfg(feature = "alloc")]
41pub(crate) fn index_to_name(fd: impl AsFd, index: u32) -> io::Result<String> {
42 let mut ifreq = ifreq {
43 ifr_ifrn: ifreq__bindgen_ty_1 { ifrn_name: [0; 16] },
44 ifr_ifru: ifreq__bindgen_ty_2 {
45 ifru_ivalue: index as _,
46 },
47 };
48
49 unsafe { ioctl(fd.as_fd(), SIOCGIFNAME, &mut ifreq as *mut ifreq as _) }?;
50
51 if let Some(nul_byte) = unsafe { ifreq.ifr_ifrn.ifrn_name }
52 .iter()
53 .position(|ch| *ch == 0)
54 {
55 let ifrn_name = unsafe { &ifreq.ifr_ifrn.ifrn_name[..nul_byte] };
56
57 // SAFETY: Convert `&[c_char]` to `&[u8]`.
58 let ifrn_name =
59 unsafe { slice::from_raw_parts(ifrn_name.as_ptr().cast::<u8>(), ifrn_name.len()) };
60
61 str::from_utf8(ifrn_name)
62 .map_err(|_| io::Errno::ILSEQ)
63 .map(ToOwned::to_owned)
64 } else {
65 Err(io::Errno::INVAL)
66 }
67}
68