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