Skip to content

Commit f935025

Browse files
authored
Merge pull request #152 from shellrow/feat-mobile-improvement
Mobile improvement
2 parents 490281d + 48ea7ab commit f935025

4 files changed

Lines changed: 135 additions & 26 deletions

File tree

‎src/os/android/interface.rs‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,32 @@ fn calc_v6_scope_id(addr: &Ipv6Addr, ifindex: u32) -> u32 {
4646
}
4747
}
4848

49+
fn finalize_interface(iface: &mut Interface) {
50+
if let Some(sysfs_type) = super::sysfs::get_interface_type(&iface.name) {
51+
iface.if_type = sysfs_type;
52+
} else if let Some(guessed_type) = super::types::guess_type_by_name(&iface.name) {
53+
iface.if_type = guessed_type;
54+
}
55+
56+
if iface.transmit_speed.is_none() || iface.receive_speed.is_none() {
57+
let speed = super::sysfs::get_interface_speed(&iface.name);
58+
if iface.transmit_speed.is_none() {
59+
iface.transmit_speed = speed;
60+
}
61+
if iface.receive_speed.is_none() {
62+
iface.receive_speed = speed;
63+
}
64+
}
65+
66+
if iface.stats.is_none() {
67+
iface.stats = crate::stats::counters::get_stats_from_name(&iface.name);
68+
}
69+
70+
if iface.mtu.is_none() {
71+
iface.mtu = crate::os::linux::mtu::get_mtu(&iface.name);
72+
}
73+
}
74+
4975
pub fn interfaces() -> Vec<Interface> {
5076
let mut ifaces: Vec<Interface> = Vec::new();
5177

@@ -91,15 +117,13 @@ pub fn interfaces() -> Vec<Interface> {
91117
Err(_) => {
92118
// fallback: unix ifaddrs
93119
ifaces = unix_interfaces();
94-
95-
for iface in &mut ifaces {
96-
if let Some(t) = super::types::guess_type_by_name(&iface.name) {
97-
iface.if_type = t;
98-
}
99-
}
100120
}
101121
}
102122

123+
for iface in &mut ifaces {
124+
finalize_interface(iface);
125+
}
126+
103127
// Fill gateway info
104128
#[cfg(feature = "gateway")]
105129
{

‎src/os/android/mod.rs‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ pub mod flags;
22
pub mod interface;
33
pub mod netlink;
44
pub mod state;
5+
pub mod sysfs;
56
pub mod types;
67

8+
use dlopen2::raw::Library;
79
use once_cell::sync::OnceCell;
810

911
pub fn get_libc_ifaddrs() -> Option<(
@@ -18,19 +20,13 @@ pub fn get_libc_ifaddrs() -> Option<(
1820

1921
fn load_symbol<T>(sym: &'static str) -> Option<T> {
2022
const LIB_NAME: &str = "libc.so";
23+
static LIBC: OnceCell<Option<Library>> = OnceCell::new();
2124

22-
match dlopen2::raw::Library::open(LIB_NAME) {
23-
Ok(lib) => match unsafe { lib.symbol::<T>(sym) } {
24-
Ok(val) => Some(val),
25-
Err(err) => {
26-
eprintln!("failed to load symbol {} from {}: {:?}", sym, LIB_NAME, err);
27-
None
28-
}
29-
},
30-
Err(err) => {
31-
eprintln!("failed to load {}: {:?}", LIB_NAME, err);
32-
None
33-
}
25+
let lib = LIBC.get_or_init(|| Library::open(LIB_NAME).ok()).as_ref()?;
26+
27+
match unsafe { lib.symbol::<T>(sym) } {
28+
Ok(val) => Some(val),
29+
Err(_) => None,
3430
}
3531
}
3632

‎src/os/android/sysfs.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use crate::interface::types::InterfaceType;
2+
use std::convert::TryFrom;
3+
use std::fs;
4+
use std::path::{Path, PathBuf};
5+
6+
fn read_trimmed(path: impl AsRef<Path>) -> Option<String> {
7+
fs::read_to_string(path).ok().map(|s| s.trim().to_owned())
8+
}
9+
10+
fn exists(path: impl AsRef<Path>) -> bool {
11+
Path::new(path.as_ref()).exists()
12+
}
13+
14+
fn is_wifi_interface(ifname: &str) -> bool {
15+
let base = PathBuf::from("/sys/class/net").join(ifname);
16+
17+
if let Some(uevent) = read_trimmed(base.join("uevent")) {
18+
if uevent.lines().any(|line| line.trim() == "DEVTYPE=wlan") {
19+
return true;
20+
}
21+
}
22+
23+
exists(base.join("wireless")) || exists(base.join("phy80211"))
24+
}
25+
26+
pub fn get_interface_type(ifname: &str) -> Option<InterfaceType> {
27+
if is_wifi_interface(ifname) {
28+
return Some(InterfaceType::Wireless80211);
29+
}
30+
31+
let path = PathBuf::from("/sys/class/net").join(ifname).join("type");
32+
let value = read_trimmed(path)?.parse::<u32>().ok()?;
33+
34+
if value == crate::os::linux::arp::ARPHRD_ETHER {
35+
Some(InterfaceType::Ethernet)
36+
} else {
37+
InterfaceType::try_from(value).ok()
38+
}
39+
}
40+
41+
pub fn get_interface_speed(ifname: &str) -> Option<u64> {
42+
let path = PathBuf::from("/sys/class/net").join(ifname).join("speed");
43+
let speed_mbps = read_trimmed(path)?.parse::<i64>().ok()?;
44+
if speed_mbps <= 0 {
45+
return None;
46+
}
47+
48+
Some((speed_mbps as u64) * 1_000_000)
49+
}

‎src/os/unix/interface.rs‎

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,10 @@ fn unix_interfaces_inner(
4444
let c_str = addr_ref.ifa_name as *const c_char;
4545
let bytes = unsafe { CStr::from_ptr(c_str).to_bytes() };
4646
let name: String = unsafe { from_utf8_unchecked(bytes).to_owned() };
47+
let if_index = if_nametoindex_or_zero(&name);
4748
let cap: libc::socklen_t = super::sockaddr::sockaddr_storage_cap();
4849
let addr_len_opt = unsafe { compute_sockaddr_len(addr_ref.ifa_addr, None, Some(cap)) };
49-
let (mac, ip, ipv6_scope_id) = match addr_len_opt {
50+
let (mac, ip, mut ipv6_scope_id) = match addr_len_opt {
5051
Some(addr_len) => {
5152
let mac = unsafe {
5253
try_mac_from_raw(addr_ref.ifa_addr as *const libc::sockaddr, addr_len)
@@ -99,10 +100,9 @@ fn unix_interfaces_inner(
99100
};
100101
match Ipv6Net::with_netmask(ipv6, netmask) {
101102
Ok(ipv6_net) => {
103+
let scope_id = resolve_ipv6_scope_id(&ipv6, ipv6_scope_id, if_index);
102104
ini_ipv6 = Some(ipv6_net);
103-
if ipv6_scope_id.is_none() {
104-
panic!("IPv6 address without scope ID!")
105-
}
105+
ipv6_scope_id = Some(scope_id);
106106
}
107107
Err(_) => {}
108108
};
@@ -137,7 +137,7 @@ fn unix_interfaces_inner(
137137
}
138138
if !found {
139139
let interface: Interface = Interface {
140-
index: 0, // We will set these below
140+
index: if_index,
141141
name: name.clone(),
142142
friendly_name: None,
143143
description: None,
@@ -176,10 +176,50 @@ fn unix_interfaces_inner(
176176
freeifaddrs(addrs);
177177
}
178178
for iface in &mut ifaces {
179-
let name = CString::new(iface.name.as_bytes()).unwrap();
180-
unsafe {
181-
iface.index = libc::if_nametoindex(name.as_ptr());
179+
if iface.index == 0 {
180+
iface.index = if_nametoindex_or_zero(&iface.name);
182181
}
183182
}
184183
ifaces
185184
}
185+
186+
fn if_nametoindex_or_zero(name: &str) -> u32 {
187+
match CString::new(name.as_bytes()) {
188+
Ok(name) => unsafe { libc::if_nametoindex(name.as_ptr()) },
189+
Err(_) => 0,
190+
}
191+
}
192+
193+
fn resolve_ipv6_scope_id(addr: &Ipv6Addr, raw_scope_id: Option<u32>, if_index: u32) -> u32 {
194+
match raw_scope_id {
195+
Some(scope_id) if scope_id != 0 => scope_id,
196+
_ if addr.is_unicast_link_local() => if_index,
197+
_ => 0,
198+
}
199+
}
200+
201+
#[cfg(test)]
202+
mod tests {
203+
use super::resolve_ipv6_scope_id;
204+
use std::net::Ipv6Addr;
205+
206+
#[test]
207+
fn preserves_non_zero_ipv6_scope_id() {
208+
let addr = "fe80::1".parse::<Ipv6Addr>().unwrap();
209+
assert_eq!(resolve_ipv6_scope_id(&addr, Some(9), 3), 9);
210+
}
211+
212+
#[test]
213+
fn derives_link_local_scope_from_interface_index() {
214+
let addr = "fe80::1".parse::<Ipv6Addr>().unwrap();
215+
assert_eq!(resolve_ipv6_scope_id(&addr, None, 7), 7);
216+
assert_eq!(resolve_ipv6_scope_id(&addr, Some(0), 7), 7);
217+
}
218+
219+
#[test]
220+
fn keeps_global_ipv6_scope_id_zero() {
221+
let addr = "2001:db8::1".parse::<Ipv6Addr>().unwrap();
222+
assert_eq!(resolve_ipv6_scope_id(&addr, None, 7), 0);
223+
assert_eq!(resolve_ipv6_scope_id(&addr, Some(0), 7), 0);
224+
}
225+
}

0 commit comments

Comments
 (0)