diff options
| author | Linus Färnstrand <linus@mullvad.net> | 2023-08-03 10:21:47 +0200 |
|---|---|---|
| committer | Linus Färnstrand <linus@mullvad.net> | 2023-08-08 08:40:05 +0200 |
| commit | 4434de4fdb50f68af1a3397dec2a4338b8ef874b (patch) | |
| tree | 1db11d9cf7a8d8d8c255dadb2a5860e8964cd2dd | |
| parent | e350149d6dd85834cfa7b3dee4a959854cf5302b (diff) | |
| download | mullvadvpn-4434de4fdb50f68af1a3397dec2a4338b8ef874b.tar.xz mullvadvpn-4434de4fdb50f68af1a3397dec2a4338b8ef874b.zip | |
Convert talpid-routing to windows-sys 0.48
| -rw-r--r-- | talpid-routing/src/windows/default_route_monitor.rs | 56 | ||||
| -rw-r--r-- | talpid-routing/src/windows/get_best_default_route.rs | 33 | ||||
| -rw-r--r-- | talpid-routing/src/windows/route_manager.rs | 64 | ||||
| -rw-r--r-- | talpid-windows-net/src/net.rs | 2 |
4 files changed, 54 insertions, 101 deletions
diff --git a/talpid-routing/src/windows/default_route_monitor.rs b/talpid-routing/src/windows/default_route_monitor.rs index 128c2533e0..dbc0615e43 100644 --- a/talpid-routing/src/windows/default_route_monitor.rs +++ b/talpid-routing/src/windows/default_route_monitor.rs @@ -5,15 +5,15 @@ use super::{ use std::{ ffi::c_void, - io, sync::{ mpsc::{channel, RecvTimeoutError, Sender}, Arc, Mutex, }, time::{Duration, Instant}, }; +use talpid_types::win32_err; use windows_sys::Win32::{ - Foundation::{BOOLEAN, HANDLE, NO_ERROR}, + Foundation::{BOOLEAN, HANDLE}, NetworkManagement::{ IpHelper::{ CancelMibChangeNotify2, ConvertInterfaceLuidToIndex, NotifyIpInterfaceChange, @@ -65,12 +65,11 @@ impl DefaultRouteMonitorContext { let mut default_interface_index = 0; let route_luid = best_route.iface; // SAFETY: No clear safety specifications - if NO_ERROR as i32 - == unsafe { ConvertInterfaceLuidToIndex(&route_luid, &mut default_interface_index) } - { - self.refresh_current_route = index == default_interface_index; - } else { - self.refresh_current_route = true; + match win32_err!(unsafe { + ConvertInterfaceLuidToIndex(&route_luid, &mut default_interface_index) + }) { + Ok(()) => self.refresh_current_route = index == default_interface_index, + Err(_) => self.refresh_current_route = true, } } } @@ -143,12 +142,10 @@ impl Drop for NotifyChangeHandle { // SAFETY: There is no clear safety specification on this function. However self.0 should // point to a handle that has been allocated by windows and should be non-null. Even // if it would be null that would cause a panic rather than UB. - unsafe { - if NO_ERROR as i32 != CancelMibChangeNotify2(self.0) { - // If this callback is called after we free the context that could result in UB, in - // order to avoid that we panic. - panic!("Could not cancel change notification callback") - } + if let Err(e) = win32_err!(unsafe { CancelMibChangeNotify2(self.0) }) { + // If this callback is called after we free the context that could result in UB, in + // order to avoid that we panic. + panic!("Could not cancel change notification callback: {}", e) } } } @@ -243,7 +240,7 @@ impl DefaultRouteMonitor { let mut handle_ptr = 0; // SAFETY: No clear safety specifications, context_ptr must be valid for as long as handle // has not been dropped. - let status = unsafe { + win32_err!(unsafe { NotifyRouteChange2( family, Some(route_change_callback), @@ -251,19 +248,14 @@ impl DefaultRouteMonitor { WIN_FALSE, &mut handle_ptr, ) - }; - - if NO_ERROR as i32 != status { - return Err(Error::RegisterNotifyRouteCallback( - io::Error::from_raw_os_error(status), - )); - } + }) + .map_err(Error::RegisterNotifyRouteCallback)?; let notify_route_change_handle = NotifyChangeHandle(handle_ptr); let mut handle_ptr = 0; // SAFETY: No clear safety specifications, context_ptr must be valid for as long as handle // has not been dropped. - let status = unsafe { + win32_err!(unsafe { NotifyIpInterfaceChange( family, Some(interface_change_callback), @@ -271,18 +263,14 @@ impl DefaultRouteMonitor { WIN_FALSE, &mut handle_ptr, ) - }; - if NO_ERROR as i32 != status { - return Err(Error::RegisterNotifyIpInterfaceCallback( - io::Error::from_raw_os_error(status), - )); - } + }) + .map_err(Error::RegisterNotifyIpInterfaceCallback)?; let notify_interface_change_handle = NotifyChangeHandle(handle_ptr); let mut handle_ptr = 0; // SAFETY: No clear safety specifications, context_ptr must be valid for as long as handle // has not been dropped. - let status = unsafe { + win32_err!(unsafe { NotifyUnicastIpAddressChange( family, Some(ip_address_change_callback), @@ -290,12 +278,8 @@ impl DefaultRouteMonitor { WIN_FALSE, &mut handle_ptr, ) - }; - if NO_ERROR as i32 != status { - return Err(Error::RegisterNotifyUnicastIpAddressCallback( - io::Error::from_raw_os_error(status), - )); - } + }) + .map_err(Error::RegisterNotifyUnicastIpAddressCallback)?; let notify_address_change_handle = NotifyChangeHandle(handle_ptr); Ok(( diff --git a/talpid-routing/src/windows/get_best_default_route.rs b/talpid-routing/src/windows/get_best_default_route.rs index 4f131e2b53..4a1f254a79 100644 --- a/talpid-routing/src/windows/get_best_default_route.rs +++ b/talpid-routing/src/windows/get_best_default_route.rs @@ -1,18 +1,16 @@ use super::{Error, Result}; -use std::{io, net::SocketAddr, slice}; +use std::{net::SocketAddr, slice}; +use talpid_types::win32_err; use talpid_windows_net::{ get_ip_interface_entry, try_socketaddr_from_inet_sockaddr, AddressFamily, }; use widestring::{widecstr, WideCStr}; -use windows_sys::Win32::{ - Foundation::NO_ERROR, - NetworkManagement::{ - IpHelper::{ - FreeMibTable, GetIfEntry2, GetIpForwardTable2, IF_TYPE_SOFTWARE_LOOPBACK, - IF_TYPE_TUNNEL, MIB_IF_ROW2, MIB_IPFORWARD_ROW2, - }, - Ndis::NET_LUID_LH, +use windows_sys::Win32::NetworkManagement::{ + IpHelper::{ + FreeMibTable, GetIfEntry2, GetIpForwardTable2, IF_TYPE_SOFTWARE_LOOPBACK, IF_TYPE_TUNNEL, + MIB_IF_ROW2, MIB_IPFORWARD_ROW2, }, + Ndis::NET_LUID_LH, }; // Interface description substrings found for virtual adapters. @@ -28,12 +26,8 @@ fn get_ip_forward_table(family: AddressFamily) -> Result<Vec<MIB_IPFORWARD_ROW2> // SAFETY: GetIpForwardTable2 does not have clear safety specifications however what it does is // heap allocate a IpForwardTable2 and then change table_ptr to point to that allocation. - let status = unsafe { GetIpForwardTable2(family, &mut table_ptr) }; - if NO_ERROR as i32 != status { - return Err(Error::GetIpForwardTableFailed( - io::Error::from_raw_os_error(status), - )); - } + win32_err!(unsafe { GetIpForwardTable2(family, &mut table_ptr) }) + .map_err(Error::GetIpForwardTableFailed)?; // SAFETY: table_ptr is valid since GetIpForwardTable2 did not return an error let num_entries = usize::try_from(unsafe { *table_ptr }.NumEntries).unwrap(); @@ -50,7 +44,7 @@ fn get_ip_forward_table(family: AddressFamily) -> Result<Vec<MIB_IPFORWARD_ROW2> // MIB_IPFORWARD_TABLE2 This pointer is ONLY deallocated here so it is guaranteed to not // have been already deallocated. We have cloned all MIB_IPFORWARD_ROW2s and the rows do not // contain pointers to the table so they will not be dangling after this free. - unsafe { FreeMibTable(table_ptr as *const _) } + unsafe { FreeMibTable(table_ptr as *const _) }; Ok(rows) } @@ -133,12 +127,7 @@ fn is_route_on_physical_interface(route: &MIB_IPFORWARD_ROW2) -> Result<bool> { // SAFETY: GetIfEntry2 does not have clear safety rules however it will read the // row.InterfaceLuid or row.InterfaceIndex and use that information to populate the struct. // We guarantee here that these fields are valid since they are set. - let status = unsafe { GetIfEntry2(&mut row) }; - if NO_ERROR as i32 != status { - return Err(Error::GetIfEntryFailed(io::Error::from_raw_os_error( - status, - ))); - } + win32_err!(unsafe { GetIfEntry2(&mut row) }).map_err(Error::GetIfEntryFailed)?; let row_description = WideCStr::from_slice_truncate(&row.Description) .expect("Windows provided incorrectly formatted utf16 string"); diff --git a/talpid-routing/src/windows/route_manager.rs b/talpid-routing/src/windows/route_manager.rs index 14fbbf3f52..277832eaa9 100644 --- a/talpid-routing/src/windows/route_manager.rs +++ b/talpid-routing/src/windows/route_manager.rs @@ -10,6 +10,7 @@ use std::{ net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, sync::{Arc, Mutex}, }; +use talpid_types::win32_err; use talpid_windows_net::{ inet_sockaddr_from_socketaddr, try_socketaddr_from_inet_sockaddr, AddressFamily, }; @@ -17,7 +18,7 @@ use widestring::{WideCStr, WideCString}; use windows_sys::Win32::{ Foundation::{ ERROR_BUFFER_OVERFLOW, ERROR_NOT_FOUND, ERROR_NO_DATA, ERROR_OBJECT_ALREADY_EXISTS, - ERROR_SUCCESS, NO_ERROR, + ERROR_SUCCESS, }, NetworkManagement::{ IpHelper::{ @@ -215,18 +216,17 @@ impl RouteManagerInternal { // // The simplest thing in this case is to just overwrite the route. // - - if ERROR_OBJECT_ALREADY_EXISTS as i32 == status { + if ERROR_OBJECT_ALREADY_EXISTS == status { // SAFETY: DestinationPrefix must be initialized to a valid prefix. NextHop must have // a valid IP address and family. At least one of InterfaceLuid and InterfaceIndex must // be set to the interface. status = unsafe { SetIpForwardEntry2(&spec) }; } - if NO_ERROR as i32 != status { + win32_err!(status).map_err(|e| { log::error!("Could not register route in routing table"); - return Err(Error::AddToRouteTable(io::Error::from_raw_os_error(status))); - } + Error::AddToRouteTable(e) + })?; Ok(RegisteredRoute { network: route.network, @@ -263,15 +263,10 @@ impl RouteManagerInternal { None => { let mut luid = NET_LUID_LH { Value: 0 }; // SAFETY: No specific safety requirement - if NO_ERROR as i32 - != unsafe { - ConvertInterfaceAliasToLuid(device_name.as_ptr(), &mut luid) - } - { - log::error!( - "Unable to derive interface LUID from interface alias: {:?}", - device_name - ); + if let Err(e) = win32_err!(unsafe { + ConvertInterfaceAliasToLuid(device_name.as_ptr(), &mut luid) + }) { + log::error!("Unable to get interface LUID for interface \"{device_name:?}\": {e}"); return Err(Error::DeviceNameNotFound); } else { luid @@ -355,26 +350,17 @@ impl RouteManagerInternal { // SAFETY: DestinationPrefix must be initialized to a valid prefix. NextHop must have // a valid IP address and family. At least one of InterfaceLuid and InterfaceIndex must be // set to the interface. - let status = unsafe { DeleteIpForwardEntry2(&r) }; - - match u32::try_from(status) { - Ok(ERROR_NOT_FOUND) => { - log::warn!("Attempting to delete route which was not present in routing table, ignoring and proceeding. Route: {}", route); + match win32_err!(unsafe { DeleteIpForwardEntry2(&r) }) { + Ok(()) => Ok(()), + Err(e) if e.raw_os_error() == Some(ERROR_NOT_FOUND as i32) => { + log::warn!("Attempting to delete route which was not present in routing table, ignoring and proceeding. Route: {route}"); + Ok(()) } - Ok(NO_ERROR) => (), - _ => { - log::error!( - "Failed to delete route in routing table. Route: {}, Status: {}", - route, - status - ); - return Err(Error::DeleteFromRouteTable(io::Error::from_raw_os_error( - status, - ))); + Err(e) => { + log::error!("Failed to delete route in routing table. Route: {route}, Error: {e}"); + Err(Error::DeleteFromRouteTable(e)) } } - - Ok(()) } fn restore_into_routing_table(route: &RegisteredRoute) -> Result<()> { @@ -396,16 +382,10 @@ impl RouteManagerInternal { // SAFETY: DestinationPrefix must be initialized to a valid prefix. NextHop must have a // valid IP address and family. At least one of InterfaceLuid and InterfaceIndex must be set // to the interface. - let status = unsafe { CreateIpForwardEntry2(&spec) }; - - if NO_ERROR as i32 != status { - log::error!( - "Could not register route in routing table. Route: {}, Status: {}", - route, - status - ); - return Err(Error::AddToRouteTable(io::Error::from_raw_os_error(status))); - } + win32_err!(unsafe { CreateIpForwardEntry2(&spec) }).map_err(|e| { + log::error!("Could not register route in routing table. Route: {route}"); + Error::AddToRouteTable(e) + })?; Ok(()) } diff --git a/talpid-windows-net/src/net.rs b/talpid-windows-net/src/net.rs index 3c0d4d6880..ec146a5c72 100644 --- a/talpid-windows-net/src/net.rs +++ b/talpid-windows-net/src/net.rs @@ -348,7 +348,7 @@ pub fn get_unicast_table( for i in 0..unsafe { *unicast_table }.NumEntries { unicast_rows.push(unsafe { *(first_row.offset(i as isize)) }); } - unsafe { FreeMibTable(unicast_table as *mut _) }; + unsafe { FreeMibTable(unicast_table as *const _) }; Ok(unicast_rows) } |
