@@ -42,11 +42,43 @@ cfg_if! {
42
42
}
43
43
}
44
44
45
+ /// Workaround a bug in XNU where netmasks will always have the wrong size in
46
+ /// the sa_len field due to the kernel ignoring trailing zeroes in the structure
47
+ /// when setting the field. See https://github.com/nix-rust/nix/issues/1709#issuecomment-1199304470
48
+ ///
49
+ /// To fix this, we overwrite `sa_len` to have the known (static) value of the
50
+ /// structure.
51
+ #[ cfg( target_os = "macos" ) ]
52
+ fn workaround_xnu_bug ( info : & libc:: ifaddrs ) {
53
+ if info. ifa_netmask . is_null ( ) {
54
+ return
55
+ }
56
+ let family = unsafe {
57
+ ( * info. ifa_netmask ) . sa_family
58
+ } ;
59
+
60
+ let fixup_size = match i32:: from ( family) {
61
+ libc:: AF_INET => std:: mem:: size_of :: < libc:: sockaddr_in > ( ) ,
62
+ libc:: AF_INET6 => std:: mem:: size_of :: < libc:: sockaddr_in6 > ( ) ,
63
+ _ => return
64
+ } ;
65
+
66
+ assert ! ( fixup_size < u8 :: MAX . into( ) ) ;
67
+ let sock = info. ifa_netmask ;
68
+ unsafe {
69
+ ( * sock) . sa_len = ( * sock) . sa_len . max ( fixup_size as u8 ) ;
70
+ }
71
+ }
72
+
45
73
impl InterfaceAddress {
46
74
/// Create an `InterfaceAddress` from the libc struct.
47
75
fn from_libc_ifaddrs ( info : & libc:: ifaddrs ) -> InterfaceAddress {
48
76
let ifname = unsafe { ffi:: CStr :: from_ptr ( info. ifa_name ) } ;
49
77
let address = unsafe { SockaddrStorage :: from_raw ( info. ifa_addr , None ) } ;
78
+ #[ cfg( target_os = "macos" ) ]
79
+ {
80
+ workaround_xnu_bug ( info)
81
+ }
50
82
let netmask = unsafe { SockaddrStorage :: from_raw ( info. ifa_netmask , None ) } ;
51
83
let mut addr = InterfaceAddress {
52
84
interface_name : ifname. to_string_lossy ( ) . to_string ( ) ,
@@ -144,4 +176,21 @@ mod tests {
144
176
fn test_getifaddrs ( ) {
145
177
let _ = getifaddrs ( ) ;
146
178
}
179
+
180
+ #[ test]
181
+ fn test_getifaddrs_netmask_correct ( ) {
182
+ let addrs = getifaddrs ( ) . unwrap ( ) ;
183
+ for iface in addrs {
184
+ let sock = if let Some ( sock) = iface. netmask {
185
+ sock
186
+ } else {
187
+ continue
188
+ } ;
189
+ if sock. family ( ) == Some ( crate :: sys:: socket:: AddressFamily :: Inet ) {
190
+ let _ = sock. as_sockaddr_in ( ) . unwrap ( ) ;
191
+ return ;
192
+ }
193
+ }
194
+ panic ! ( "No address?" ) ;
195
+ }
147
196
}
0 commit comments