feat: merge subscriptions crate into cosmic-settings repo
This commit is contained in:
parent
a2f53f2239
commit
600720b7d1
47 changed files with 8399 additions and 63 deletions
67
subscriptions/network-manager/src/active_conns.rs
Normal file
67
subscriptions/network-manager/src/active_conns.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// Copyright 2024 System76 <info@system76.com>
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use super::Event;
|
||||
use cosmic_dbus_networkmanager::nm::NetworkManager;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use iced_futures::{Subscription, stream};
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
use zbus::Connection;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum State {
|
||||
Continue(Connection),
|
||||
Error,
|
||||
}
|
||||
|
||||
pub fn active_conns_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
|
||||
id: I,
|
||||
conn: Connection,
|
||||
) -> iced_futures::Subscription<Event> {
|
||||
Subscription::run_with_id(
|
||||
id,
|
||||
stream::channel(50, move |output| async move {
|
||||
watch(conn, output).await;
|
||||
futures::future::pending().await
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn watch(conn: zbus::Connection, mut output: futures::channel::mpsc::Sender<Event>) {
|
||||
let mut state = State::Continue(conn);
|
||||
|
||||
loop {
|
||||
state = start_listening(state, &mut output).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_listening(
|
||||
state: State,
|
||||
output: &mut futures::channel::mpsc::Sender<Event>,
|
||||
) -> State {
|
||||
let conn = match state {
|
||||
State::Continue(conn) => conn,
|
||||
State::Error => futures::future::pending().await,
|
||||
};
|
||||
let network_manager = match NetworkManager::new(&conn).await {
|
||||
Ok(n) => n,
|
||||
Err(why) => {
|
||||
tracing::error!(why = why.to_string(), "Failed to connect to NetworkManager");
|
||||
return State::Error;
|
||||
}
|
||||
};
|
||||
|
||||
let mut active_conns_changed = network_manager.receive_active_connections_changed().await;
|
||||
active_conns_changed.next().await;
|
||||
|
||||
while let (Some(_change), _) = futures::future::join(
|
||||
active_conns_changed.next(),
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(1)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
_ = output.send(Event::ActiveConns).await;
|
||||
}
|
||||
|
||||
State::Continue(conn)
|
||||
}
|
||||
120
subscriptions/network-manager/src/available_wifi.rs
Normal file
120
subscriptions/network-manager/src/available_wifi.rs
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
// Copyright 2024 System76 <info@system76.com>
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use cosmic_dbus_networkmanager::{
|
||||
device::wireless::WirelessDevice,
|
||||
interface::enums::{ApFlags, ApSecurityFlags, DeviceState},
|
||||
};
|
||||
|
||||
use futures::StreamExt;
|
||||
use itertools::Itertools;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
use zbus::zvariant::ObjectPath;
|
||||
|
||||
use super::hw_address::HwAddress;
|
||||
|
||||
pub async fn handle_wireless_device(
|
||||
device: WirelessDevice<'_>,
|
||||
hw_address: Option<String>,
|
||||
) -> zbus::Result<Vec<AccessPoint>> {
|
||||
device.request_scan(HashMap::new()).await?;
|
||||
|
||||
let mut scan_changed = device.receive_last_scan_changed().await;
|
||||
|
||||
if let Some(t) = scan_changed.next().await {
|
||||
match t.get().await {
|
||||
Ok(-1) => {
|
||||
tracing::error!("wireless device scan errored");
|
||||
return Ok(Default::default());
|
||||
}
|
||||
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
let access_points = device.get_access_points().await?;
|
||||
|
||||
let state: DeviceState = device
|
||||
.upcast()
|
||||
.await
|
||||
.and_then(|dev| dev.cached_state())
|
||||
.unwrap_or_default()
|
||||
.map(|s| s.into())
|
||||
.unwrap_or_else(|| DeviceState::Unknown);
|
||||
|
||||
// Sort by strength and remove duplicates
|
||||
let mut aps = HashMap::<String, AccessPoint>::new();
|
||||
for ap in access_points {
|
||||
let (ssid_res, strength_res) = futures::join!(ap.ssid(), ap.strength());
|
||||
|
||||
if let Some((ssid, strength)) = ssid_res.ok().zip(strength_res.ok()) {
|
||||
let ssid = String::from_utf8_lossy(&ssid.clone()).into_owned();
|
||||
if let Some(access_point) = aps.get(&ssid) {
|
||||
if access_point.strength > strength {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let Ok(flags) = ap.rsn_flags().await else {
|
||||
continue;
|
||||
};
|
||||
let network_type = if flags.intersects(ApSecurityFlags::KEY_MGMT_802_1X) {
|
||||
NetworkType::EAP
|
||||
} else if flags.intersects(ApSecurityFlags::KEY_MGMTPSK) {
|
||||
NetworkType::PSK
|
||||
} else if flags.is_empty() {
|
||||
NetworkType::Open
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
aps.insert(
|
||||
ssid.clone(),
|
||||
AccessPoint {
|
||||
ssid: Arc::from(ssid),
|
||||
strength,
|
||||
state,
|
||||
working: false,
|
||||
path: ap.inner().path().to_owned(),
|
||||
secured: !ap.wpa_flags().await?.is_empty(),
|
||||
wps_push: ap.flags().await?.contains(ApFlags::WPS_PBC),
|
||||
network_type,
|
||||
hw_address: hw_address
|
||||
.as_ref()
|
||||
.and_then(|str_addr| HwAddress::from_str(str_addr))
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let aps = aps
|
||||
.into_values()
|
||||
.sorted_by(|a, b| b.strength.cmp(&a.strength))
|
||||
.collect();
|
||||
|
||||
Ok(aps)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccessPoint {
|
||||
pub ssid: Arc<str>,
|
||||
pub strength: u8,
|
||||
pub state: DeviceState,
|
||||
pub working: bool,
|
||||
pub path: ObjectPath<'static>,
|
||||
pub hw_address: HwAddress,
|
||||
pub secured: bool,
|
||||
pub wps_push: bool,
|
||||
pub network_type: NetworkType,
|
||||
}
|
||||
|
||||
// TODO do we want to support eap methods other than peap in the applet?
|
||||
// Then we'd need a dropdown for the eap method,
|
||||
// and tls requires a cert instead of a password
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NetworkType {
|
||||
Open,
|
||||
PSK,
|
||||
EAP,
|
||||
}
|
||||
112
subscriptions/network-manager/src/current_networks.rs
Normal file
112
subscriptions/network-manager/src/current_networks.rs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
// Copyright 2024 System76 <info@system76.com>
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use cosmic_dbus_networkmanager::{
|
||||
active_connection::ActiveConnection, device::SpecificDevice,
|
||||
interface::enums::ActiveConnectionState,
|
||||
};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub async fn active_connections(
|
||||
active_connections: Vec<ActiveConnection<'_>>,
|
||||
) -> zbus::Result<Vec<ActiveConnectionInfo>> {
|
||||
let mut info = Vec::<ActiveConnectionInfo>::with_capacity(active_connections.len());
|
||||
for connection in active_connections {
|
||||
let ipv4 = connection
|
||||
.ip4_config()
|
||||
.await?
|
||||
.address_data()
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let addresses: Vec<_> = ipv4.iter().map(|d| d.address).collect();
|
||||
let state = connection
|
||||
.state()
|
||||
.await
|
||||
.unwrap_or(ActiveConnectionState::Unknown);
|
||||
|
||||
if connection.vpn().await.unwrap_or_default() {
|
||||
info.push(ActiveConnectionInfo::Vpn {
|
||||
name: connection.id().await?,
|
||||
ip_addresses: addresses.clone(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
for device in connection.devices().await.unwrap_or_default() {
|
||||
match device
|
||||
.downcast_to_device()
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|inner| inner)
|
||||
{
|
||||
Some(SpecificDevice::Wired(wired_device)) => {
|
||||
info.push(ActiveConnectionInfo::Wired {
|
||||
name: connection.id().await?,
|
||||
hw_address: wired_device.hw_address().await?,
|
||||
speed: wired_device.speed().await?,
|
||||
ip_addresses: addresses.clone(),
|
||||
});
|
||||
}
|
||||
Some(SpecificDevice::Wireless(wireless_device)) => {
|
||||
if let Ok(access_point) = wireless_device.active_access_point().await {
|
||||
info.push(ActiveConnectionInfo::WiFi {
|
||||
name: String::from_utf8_lossy(&access_point.ssid().await?).into_owned(),
|
||||
ip_addresses: addresses.clone(),
|
||||
hw_address: wireless_device.hw_address().await?,
|
||||
state,
|
||||
strength: access_point.strength().await.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(SpecificDevice::WireGuard(_)) => {
|
||||
info.push(ActiveConnectionInfo::Vpn {
|
||||
name: connection.id().await?,
|
||||
ip_addresses: addresses.clone(),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info.sort_by(|a, b| {
|
||||
let helper = |conn: &ActiveConnectionInfo| match conn {
|
||||
ActiveConnectionInfo::Vpn { name, .. } => format!("0{name}"),
|
||||
ActiveConnectionInfo::Wired { name, .. } => format!("1{name}"),
|
||||
ActiveConnectionInfo::WiFi { name, .. } => format!("2{name}"),
|
||||
};
|
||||
helper(a).cmp(&helper(b))
|
||||
});
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ActiveConnectionInfo {
|
||||
Wired {
|
||||
name: String,
|
||||
hw_address: String,
|
||||
speed: u32,
|
||||
ip_addresses: Vec<Ipv4Addr>,
|
||||
},
|
||||
WiFi {
|
||||
name: String,
|
||||
ip_addresses: Vec<Ipv4Addr>,
|
||||
hw_address: String,
|
||||
state: ActiveConnectionState,
|
||||
strength: u8,
|
||||
},
|
||||
Vpn {
|
||||
name: String,
|
||||
ip_addresses: Vec<Ipv4Addr>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ActiveConnectionInfo {
|
||||
pub fn name(&self) -> String {
|
||||
match &self {
|
||||
Self::Wired { name, .. } => name.clone(),
|
||||
Self::WiFi { name, .. } => name.clone(),
|
||||
Self::Vpn { name, .. } => name.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
230
subscriptions/network-manager/src/devices.rs
Normal file
230
subscriptions/network-manager/src/devices.rs
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
// Copyright 2024 System76 <info@system76.com>
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use super::Event;
|
||||
pub use cosmic_dbus_networkmanager::interface::enums::{
|
||||
ActiveConnectionState, DeviceState, DeviceType,
|
||||
};
|
||||
|
||||
use cosmic_dbus_networkmanager::nm::NetworkManager;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use iced_futures::{self, Subscription, stream};
|
||||
use std::{fmt::Debug, hash::Hash, sync::Arc};
|
||||
use zbus::{Connection, zvariant::ObjectPath};
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct DeviceInfo {
|
||||
pub path: ObjectPath<'static>,
|
||||
pub device_type: DeviceType,
|
||||
pub interface: String,
|
||||
pub state: DeviceState,
|
||||
pub active_connection: Option<(DeviceConnection, ActiveConnectionState)>,
|
||||
pub available_connections: Vec<DeviceConnection>,
|
||||
pub known_connections: Vec<KnownDeviceConnection>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct DeviceConnection {
|
||||
pub path: ObjectPath<'static>,
|
||||
pub id: String,
|
||||
pub uuid: Arc<str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct KnownDeviceConnection {
|
||||
pub id: String,
|
||||
pub uuid: Arc<str>,
|
||||
}
|
||||
|
||||
pub async fn list<'a>(
|
||||
conn: &'a zbus::Connection,
|
||||
device_type_filter: fn(DeviceType) -> bool,
|
||||
) -> zbus::Result<Vec<DeviceInfo>> {
|
||||
let nm = NetworkManager::new(conn).await?;
|
||||
|
||||
let (devices, nm_settings) = futures::try_join!(nm.devices(), nm.settings())?;
|
||||
|
||||
let connection_settings: &Vec<_> = &futures::stream::FuturesOrdered::from_iter(
|
||||
nm_settings
|
||||
.list_connections()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|connection| async move { connection.get_settings().await }),
|
||||
)
|
||||
.filter_map(|res| async move { res.ok() })
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
let device_iter = devices.into_iter().map(|device| async move {
|
||||
let (interface, hw_address, device_type, state, available_connections) =
|
||||
futures::try_join!(
|
||||
device.interface(),
|
||||
device.hw_address(),
|
||||
device.device_type(),
|
||||
device.state(),
|
||||
device.available_connections()
|
||||
)
|
||||
.ok()?;
|
||||
|
||||
if !device_type_filter(device_type) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if hw_address.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (active_connection, available_connections) = futures::join!(
|
||||
async {
|
||||
let connection = device.active_connection().await?;
|
||||
|
||||
let (id, uuid, state) =
|
||||
futures::try_join!(connection.id(), connection.uuid(), connection.state())?;
|
||||
|
||||
Ok::<_, zbus::Error>((
|
||||
DeviceConnection {
|
||||
id,
|
||||
uuid: Arc::from(uuid),
|
||||
path: connection.inner().path().to_owned(),
|
||||
},
|
||||
state,
|
||||
))
|
||||
},
|
||||
futures::stream::FuturesOrdered::from_iter(available_connections.into_iter().map(
|
||||
|conn| async move {
|
||||
let path = conn.inner().path().to_owned();
|
||||
|
||||
let settings = conn.get_settings().await.ok()?;
|
||||
|
||||
let id = settings
|
||||
.get("connection")?
|
||||
.get("id")?
|
||||
.downcast_ref::<String>()
|
||||
.ok()?;
|
||||
|
||||
let uuid = settings["connection"]
|
||||
.get("uuid")?
|
||||
.downcast_ref::<String>()
|
||||
.ok()?;
|
||||
|
||||
Some(DeviceConnection {
|
||||
id,
|
||||
uuid: Arc::from(uuid),
|
||||
path,
|
||||
})
|
||||
}
|
||||
),)
|
||||
.filter_map(|res| async move { res })
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
let known_connections = connection_settings
|
||||
.iter()
|
||||
.flat_map(|conn_settings| {
|
||||
let connection = conn_settings.get("connection")?;
|
||||
|
||||
let interface_name = connection
|
||||
.get("interface-name")?
|
||||
.downcast_ref::<String>()
|
||||
.ok()?;
|
||||
|
||||
if interface_name != interface {
|
||||
return None;
|
||||
}
|
||||
|
||||
let id = connection.get("id")?.downcast_ref::<String>().ok()?;
|
||||
let uuid = connection.get("uuid")?.downcast_ref::<String>().ok()?;
|
||||
|
||||
Some(KnownDeviceConnection {
|
||||
uuid: Arc::from(uuid),
|
||||
id,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(DeviceInfo {
|
||||
path: device.inner().path().to_owned(),
|
||||
device_type,
|
||||
interface,
|
||||
state,
|
||||
active_connection: active_connection.ok(),
|
||||
known_connections,
|
||||
available_connections,
|
||||
})
|
||||
});
|
||||
|
||||
let devices_info = futures::stream::FuturesOrdered::from_iter(device_iter)
|
||||
.filter_map(|res| async move { res })
|
||||
.collect::<Vec<DeviceInfo>>()
|
||||
.await;
|
||||
|
||||
Ok(devices_info)
|
||||
}
|
||||
|
||||
pub fn subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
|
||||
id: I,
|
||||
has_popup: bool,
|
||||
conn: Connection,
|
||||
) -> iced_futures::Subscription<Event> {
|
||||
Subscription::run_with_id(
|
||||
(id, has_popup),
|
||||
stream::channel(50, move |output| async move {
|
||||
watch(conn, has_popup, output).await;
|
||||
futures::future::pending().await
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn watch(
|
||||
conn: zbus::Connection,
|
||||
has_popup: bool,
|
||||
mut output: futures::channel::mpsc::Sender<Event>,
|
||||
) {
|
||||
let mut state = State::Continue(conn);
|
||||
|
||||
loop {
|
||||
state = start_listening(state, has_popup, &mut output).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum State {
|
||||
Continue(Connection),
|
||||
Error,
|
||||
}
|
||||
|
||||
async fn start_listening(
|
||||
state: State,
|
||||
has_popup: bool,
|
||||
output: &mut futures::channel::mpsc::Sender<Event>,
|
||||
) -> State {
|
||||
let conn = match state {
|
||||
State::Continue(conn) => conn,
|
||||
State::Error => futures::future::pending().await,
|
||||
};
|
||||
let network_manager = match NetworkManager::new(&conn).await {
|
||||
Ok(n) => n,
|
||||
Err(why) => {
|
||||
tracing::error!(
|
||||
why = why.to_string(),
|
||||
"failed to connect to network_manager"
|
||||
);
|
||||
return State::Error;
|
||||
}
|
||||
};
|
||||
|
||||
let mut devices_changed = network_manager.receive_devices_changed().await;
|
||||
|
||||
let secs = if has_popup { 4 } else { 60 };
|
||||
|
||||
while let (Some(_change), _) = futures::future::join(
|
||||
devices_changed.next(),
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(secs)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
_ = output.send(Event::Devices).await;
|
||||
}
|
||||
|
||||
State::Continue(conn)
|
||||
}
|
||||
34
subscriptions/network-manager/src/hw_address.rs
Normal file
34
subscriptions/network-manager/src/hw_address.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
#[derive(Copy, Clone, PartialEq, Eq, Default, Debug, PartialOrd, Ord)]
|
||||
pub struct HwAddress {
|
||||
address: u64,
|
||||
}
|
||||
|
||||
impl HwAddress {
|
||||
pub fn from_str(arg: &str) -> Option<Self> {
|
||||
let columnless_vec = arg.split(":").collect::<Vec<&str>>();
|
||||
if columnless_vec.len() * 3 - 1 != arg.len() {
|
||||
return None;
|
||||
}
|
||||
for byte in &columnless_vec {
|
||||
if byte.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
u64::from_str_radix(columnless_vec.join("").as_str(), 16)
|
||||
.ok()
|
||||
.and_then(|address| Some(HwAddress { address }))
|
||||
}
|
||||
pub fn from_string(arg: &String) -> Option<Self> {
|
||||
HwAddress::from_str(arg.as_str())
|
||||
}
|
||||
pub fn to_string(&self) -> String {
|
||||
format!("{:#x}", self.address)
|
||||
.trim_start_matches("0x")
|
||||
.chars()
|
||||
.collect::<Vec<_>>()
|
||||
.chunks(2)
|
||||
.map(|chunk| chunk.iter().cloned().collect::<String>())
|
||||
.collect::<Vec<String>>()
|
||||
.join(":")
|
||||
}
|
||||
}
|
||||
889
subscriptions/network-manager/src/lib.rs
Normal file
889
subscriptions/network-manager/src/lib.rs
Normal file
|
|
@ -0,0 +1,889 @@
|
|||
// Copyright 2024 System76 <info@system76.com>
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
pub mod active_conns;
|
||||
pub mod available_wifi;
|
||||
pub mod current_networks;
|
||||
pub mod devices;
|
||||
pub mod hw_address;
|
||||
pub mod wireless_enabled;
|
||||
|
||||
use std::{collections::HashMap, fmt::Debug, sync::Arc, time::Duration};
|
||||
|
||||
use available_wifi::NetworkType;
|
||||
pub use cosmic_dbus_networkmanager as dbus;
|
||||
pub use dbus::settings::connection::Settings;
|
||||
|
||||
use cosmic_dbus_networkmanager::{
|
||||
active_connection::ActiveConnection,
|
||||
device::SpecificDevice,
|
||||
interface::{
|
||||
active_connection::ActiveConnectionProxy,
|
||||
enums::{self, ActiveConnectionState, DeviceType, NmConnectivityState},
|
||||
},
|
||||
nm::NetworkManager,
|
||||
settings::NetworkManagerSettings,
|
||||
};
|
||||
use futures::{
|
||||
FutureExt, SinkExt, StreamExt,
|
||||
channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
|
||||
};
|
||||
use hw_address::HwAddress;
|
||||
use iced_futures::{Subscription, stream};
|
||||
use secure_string::SecureString;
|
||||
use tokio::process::Command;
|
||||
use zbus::zvariant::{self, ObjectPath, Value};
|
||||
|
||||
use self::{
|
||||
available_wifi::{AccessPoint, handle_wireless_device},
|
||||
current_networks::{ActiveConnectionInfo, active_connections},
|
||||
};
|
||||
|
||||
pub type SSID = Arc<str>;
|
||||
pub type UUID = Arc<str>;
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("access point not found")]
|
||||
AccessPointNotFound,
|
||||
#[error("failed to list bluetooth devices with rfkill")]
|
||||
BluetoothRfkillList(std::io::Error),
|
||||
#[error("failed to activate connection")]
|
||||
ConnectionActivate,
|
||||
#[error("no wifi devices found")]
|
||||
NoWiFiDevices,
|
||||
#[error("zbus error")]
|
||||
Zbus(#[from] zbus::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum State {
|
||||
Ready(zbus::Connection),
|
||||
Waiting(zbus::Connection, UnboundedReceiver<Request>),
|
||||
Finished,
|
||||
}
|
||||
|
||||
/// Reloads state on available connection changes.
|
||||
pub async fn watch_connections_changed(
|
||||
conn: zbus::Connection,
|
||||
mut output: futures::channel::mpsc::Sender<Event>,
|
||||
) {
|
||||
let Ok(nm) = NetworkManager::new(&conn).await else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut device_stream = nm.receive_devices_changed().await;
|
||||
|
||||
loop {
|
||||
// Emits updates when available connections changes.
|
||||
let connections_changed = std::pin::pin!(async {
|
||||
let devices = nm.devices().await.unwrap_or_default();
|
||||
|
||||
let mut connection_streams =
|
||||
futures::stream::FuturesUnordered::from_iter(devices.into_iter().map(
|
||||
|device| async move { device.receive_available_connections_changed().await },
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
let mut available_connections = futures::stream::FuturesUnordered::from_iter(
|
||||
connection_streams
|
||||
.iter_mut()
|
||||
.map(|stream| async { stream.next().await }),
|
||||
);
|
||||
|
||||
loop {
|
||||
_ = futures::join!(
|
||||
available_connections.next(),
|
||||
tokio::time::sleep(Duration::from_secs(3))
|
||||
);
|
||||
|
||||
// TODO: although it should consume the stream, the stream is never empty.
|
||||
// while available_connections.next().now_or_never().is_some() {}
|
||||
|
||||
let state = NetworkManagerState::new(&conn).await.unwrap_or_default();
|
||||
|
||||
_ = output
|
||||
.send(Event::RequestResponse {
|
||||
req: Request::Reload,
|
||||
state,
|
||||
success: true,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
// Reload the connection streams whenever devices change.
|
||||
futures::future::select(connections_changed, device_stream.next()).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscription<I: Copy + Debug + std::hash::Hash + 'static>(
|
||||
id: I,
|
||||
conn: zbus::Connection,
|
||||
) -> iced_futures::Subscription<Event> {
|
||||
Subscription::run_with_id(
|
||||
id,
|
||||
stream::channel(50, |output| async move {
|
||||
watch(conn, output).await;
|
||||
futures::future::pending().await
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn watch(conn: zbus::Connection, mut output: futures::channel::mpsc::Sender<Event>) {
|
||||
let mut state = State::Ready(conn);
|
||||
|
||||
loop {
|
||||
state = start_listening(state, &mut output).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_listening(
|
||||
state: State,
|
||||
output: &mut futures::channel::mpsc::Sender<Event>,
|
||||
) -> State {
|
||||
match state {
|
||||
State::Ready(conn) => {
|
||||
let (tx, rx) = unbounded();
|
||||
|
||||
if output
|
||||
.send(Event::Init {
|
||||
conn: conn.clone(),
|
||||
sender: tx,
|
||||
state: NetworkManagerState::new(&conn).await.unwrap_or_default(),
|
||||
})
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
State::Waiting(conn, rx)
|
||||
} else {
|
||||
State::Finished
|
||||
}
|
||||
}
|
||||
State::Waiting(conn, mut rx) => {
|
||||
let network_manager = match NetworkManager::new(&conn).await {
|
||||
Ok(n) => n,
|
||||
Err(_) => return State::Finished,
|
||||
};
|
||||
|
||||
match rx.next().await {
|
||||
Some(Request::Deactivate(uuid)) => {
|
||||
let mut success = false;
|
||||
for c in network_manager
|
||||
.active_connections()
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
{
|
||||
if c.uuid().await.unwrap_or_default().as_str() == uuid.as_ref()
|
||||
&& network_manager.deactivate_connection(&c).await.is_ok()
|
||||
{
|
||||
success = true;
|
||||
if let Ok(ActiveConnectionState::Deactivated) = c.state().await {
|
||||
break;
|
||||
} else {
|
||||
let mut changed = c.receive_state_changed().await;
|
||||
_ = tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
loop {
|
||||
if let Some(next) = changed.next().await {
|
||||
if let Ok(ActiveConnectionState::Deactivated) =
|
||||
next.get().await.map(ActiveConnectionState::from)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_ = request_response(&conn, Request::Deactivate(uuid.clone()), success)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::Disconnect(ssid)) => {
|
||||
let mut success = false;
|
||||
for c in network_manager
|
||||
.active_connections()
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
{
|
||||
if c.id().await.unwrap_or_default().as_str() == ssid.as_ref()
|
||||
&& network_manager.deactivate_connection(&c).await.is_ok()
|
||||
{
|
||||
success = true;
|
||||
if let Ok(ActiveConnectionState::Deactivated) = c.state().await {
|
||||
break;
|
||||
} else {
|
||||
let mut changed = c.receive_state_changed().await;
|
||||
_ = tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
loop {
|
||||
if let Some(next) = changed.next().await {
|
||||
if let Ok(ActiveConnectionState::Deactivated) =
|
||||
next.get().await.map(ActiveConnectionState::from)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_ = request_response(&conn, Request::Disconnect(ssid.clone()), success)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::SetAirplaneMode(airplane_mode)) => {
|
||||
// wifi
|
||||
let mut success = network_manager
|
||||
.set_wireless_enabled(!airplane_mode)
|
||||
.await
|
||||
.is_ok();
|
||||
// bluetooth
|
||||
success = success
|
||||
&& Command::new("rfkill")
|
||||
.arg(if airplane_mode { "block" } else { "unblock" })
|
||||
.arg("bluetooth")
|
||||
.output()
|
||||
.await
|
||||
.is_ok();
|
||||
|
||||
let mut state = NetworkManagerState::new(&conn).await.unwrap_or_default();
|
||||
state.airplane_mode = if success {
|
||||
airplane_mode
|
||||
} else {
|
||||
!airplane_mode
|
||||
};
|
||||
if state.airplane_mode {
|
||||
state.wifi_enabled = false;
|
||||
}
|
||||
|
||||
_ = output
|
||||
.send(Event::RequestResponse {
|
||||
req: Request::SetAirplaneMode(airplane_mode),
|
||||
success,
|
||||
state,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::SetWiFi(enabled)) => {
|
||||
let success = network_manager.set_wireless_enabled(enabled).await.is_ok();
|
||||
|
||||
let mut state = NetworkManagerState::new(&conn).await.unwrap_or_default();
|
||||
|
||||
state.wifi_enabled = if success { enabled } else { !enabled };
|
||||
|
||||
if state.wifi_enabled {
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
}
|
||||
|
||||
_ = request_response(&conn, Request::SetWiFi(enabled), success)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::Authenticate {
|
||||
ssid,
|
||||
identity,
|
||||
password,
|
||||
hw_address,
|
||||
}) => {
|
||||
let nm_state = NetworkManagerState::new(&conn).await.unwrap_or_default();
|
||||
let success = nm_state
|
||||
.connect_wifi(
|
||||
&conn,
|
||||
&ssid,
|
||||
identity.as_deref(),
|
||||
Some(password.unsecure()),
|
||||
hw_address,
|
||||
)
|
||||
.await
|
||||
.is_ok();
|
||||
|
||||
_ = output
|
||||
.send(Event::RequestResponse {
|
||||
req: Request::Authenticate {
|
||||
ssid: ssid.clone(),
|
||||
identity: identity.clone(),
|
||||
password: password.clone(),
|
||||
hw_address,
|
||||
},
|
||||
success,
|
||||
state: NetworkManagerState::new(&conn).await.unwrap_or_default(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::SelectAccessPoint(ssid, hw_address, network_type)) => {
|
||||
if matches!(network_type, NetworkType::Open) {
|
||||
attempt_wifi_connection(&conn, ssid, hw_address, network_type, output)
|
||||
.await;
|
||||
} else {
|
||||
// For secured networks, check if we have saved credentials
|
||||
if !has_saved_wifi_credentials(&conn, &ssid).await {
|
||||
return State::Waiting(conn, rx);
|
||||
}
|
||||
|
||||
// We have saved credentials, attempt connection
|
||||
attempt_wifi_connection(&conn, ssid, hw_address, network_type, output)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Some(Request::Activate(device_path, connection_path)) => {
|
||||
let mut success = true;
|
||||
|
||||
if let Err(why) = network_manager
|
||||
.activate_connection_by_paths(&connection_path, &device_path)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
?why,
|
||||
"failed to activate connection on {device_path:?} to {connection_path}"
|
||||
);
|
||||
success = false;
|
||||
};
|
||||
|
||||
_ = request_response(
|
||||
&conn,
|
||||
Request::Activate(device_path, connection_path),
|
||||
success,
|
||||
)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::Reload) => {
|
||||
_ = output
|
||||
.send(request_response(&conn, Request::Reload, true).await)
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::Remove(uuid)) => {
|
||||
let s = match NetworkManagerSettings::new(&conn).await {
|
||||
Ok(s) => s,
|
||||
Err(why) => {
|
||||
tracing::error!(?why, "error getting network manager settings");
|
||||
_ = output
|
||||
.send(Event::RequestResponse {
|
||||
req: Request::Forget(uuid.clone()),
|
||||
success: false,
|
||||
state: NetworkManagerState::new(&conn)
|
||||
.await
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
.await;
|
||||
|
||||
return State::Waiting(conn, rx);
|
||||
}
|
||||
};
|
||||
|
||||
let known_conns = s.list_connections().await.unwrap_or_default();
|
||||
let mut success = false;
|
||||
for c in known_conns {
|
||||
let settings = c.get_settings().await.ok().unwrap_or_default();
|
||||
|
||||
let c_uuid = settings
|
||||
.get("connection")
|
||||
.and_then(|conn| conn.get("uuid"))
|
||||
.and_then(|uuid| uuid.downcast_ref::<String>().ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
if uuid.as_ref() == c_uuid.as_str() {
|
||||
_ = c.delete().await;
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
|
||||
_ = request_response(&conn, Request::Remove(uuid.clone()), success)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
Some(Request::Forget(ssid)) => {
|
||||
let s = match NetworkManagerSettings::new(&conn).await {
|
||||
Ok(s) => s,
|
||||
Err(why) => {
|
||||
tracing::error!(?why, "error getting network manager settings");
|
||||
_ = output
|
||||
.send(Event::RequestResponse {
|
||||
req: Request::Forget(ssid.clone()),
|
||||
success: false,
|
||||
state: NetworkManagerState::new(&conn)
|
||||
.await
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
.await;
|
||||
|
||||
return State::Waiting(conn, rx);
|
||||
}
|
||||
};
|
||||
|
||||
let known_conns = s.list_connections().await.unwrap_or_default();
|
||||
let mut success = false;
|
||||
for c in known_conns {
|
||||
let settings = c.get_settings().await.ok().unwrap_or_default();
|
||||
let s = Settings::new(settings);
|
||||
if s.wifi
|
||||
.clone()
|
||||
.and_then(|w| w.ssid)
|
||||
.and_then(|ssid| String::from_utf8(ssid).ok())
|
||||
.is_some_and(|s| s == ssid.as_ref())
|
||||
{
|
||||
_ = c.delete().await;
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_ = request_response(&conn, Request::Forget(ssid.clone()), success)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
None => {
|
||||
return State::Finished;
|
||||
}
|
||||
};
|
||||
|
||||
State::Waiting(conn, rx)
|
||||
}
|
||||
State::Finished => futures::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_response(conn: &zbus::Connection, req: Request, success: bool) -> Event {
|
||||
Event::RequestResponse {
|
||||
req,
|
||||
success,
|
||||
state: NetworkManagerState::new(conn).await.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn has_saved_wifi_credentials(conn: &zbus::Connection, ssid: &str) -> bool {
|
||||
let Ok(nm_settings) = NetworkManagerSettings::new(conn).await else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let known_conns = nm_settings.list_connections().await.unwrap_or_default();
|
||||
|
||||
for connection in known_conns {
|
||||
if let Ok(settings) = connection.get_settings().await {
|
||||
let settings = Settings::new(settings);
|
||||
if let Some(saved_ssid) = settings
|
||||
.wifi
|
||||
.and_then(|w| w.ssid)
|
||||
.and_then(|ssid| String::from_utf8(ssid).ok())
|
||||
{
|
||||
if saved_ssid == ssid {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
async fn attempt_wifi_connection(
|
||||
conn: &zbus::Connection,
|
||||
ssid: SSID,
|
||||
hw_address: HwAddress,
|
||||
network_type: NetworkType,
|
||||
output: &mut futures::channel::mpsc::Sender<Event>,
|
||||
) {
|
||||
let state = NetworkManagerState::new(conn).await.unwrap_or_default();
|
||||
|
||||
let success = if let Err(err) = state
|
||||
.connect_wifi(conn, ssid.as_ref(), None, None, hw_address)
|
||||
.await
|
||||
{
|
||||
tracing::error!("Failed to connect to access point: {:?}", err);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
_ = request_response(
|
||||
conn,
|
||||
Request::SelectAccessPoint(ssid, hw_address, network_type),
|
||||
success,
|
||||
)
|
||||
.then(|event| output.send(event))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Request {
|
||||
/// Activate a device's connection profile
|
||||
Activate(ObjectPath<'static>, ObjectPath<'static>),
|
||||
/// Deactivate a connection
|
||||
Deactivate(UUID),
|
||||
/// Disconnect from an access point.
|
||||
Disconnect(SSID),
|
||||
/// Forget a known access point.
|
||||
Forget(SSID),
|
||||
/// Create a connection to a new access point.
|
||||
Authenticate {
|
||||
ssid: String,
|
||||
identity: Option<String>,
|
||||
password: SecureString,
|
||||
hw_address: HwAddress,
|
||||
},
|
||||
/// Signal to reload the service.
|
||||
Reload,
|
||||
/// Remove a connection profile.
|
||||
Remove(UUID),
|
||||
/// Connect to a known access point.
|
||||
SelectAccessPoint(SSID, HwAddress, NetworkType),
|
||||
/// Toggle airplaine mode.
|
||||
SetAirplaneMode(bool),
|
||||
/// Toggle WiFi enablement.
|
||||
SetWiFi(bool),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Event {
|
||||
RequestResponse {
|
||||
req: Request,
|
||||
state: NetworkManagerState,
|
||||
success: bool,
|
||||
},
|
||||
Init {
|
||||
conn: zbus::Connection,
|
||||
sender: UnboundedSender<Request>,
|
||||
state: NetworkManagerState,
|
||||
},
|
||||
Devices,
|
||||
WiFiEnabled(bool),
|
||||
WirelessAccessPoints,
|
||||
ActiveConns,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NetworkManagerState {
|
||||
pub wireless_access_points: Vec<AccessPoint>,
|
||||
pub active_conns: Vec<ActiveConnectionInfo>,
|
||||
pub known_access_points: Vec<AccessPoint>,
|
||||
pub wifi_enabled: bool,
|
||||
pub airplane_mode: bool,
|
||||
pub connectivity: NmConnectivityState,
|
||||
}
|
||||
|
||||
impl Default for NetworkManagerState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
wireless_access_points: Vec::new(),
|
||||
active_conns: Vec::new(),
|
||||
known_access_points: Vec::new(),
|
||||
wifi_enabled: false,
|
||||
airplane_mode: false,
|
||||
connectivity: NmConnectivityState::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkManagerState {
|
||||
pub async fn new(conn: &zbus::Connection) -> Result<Self, Error> {
|
||||
let network_manager = NetworkManager::new(conn).await?;
|
||||
let mut this = Self::default();
|
||||
|
||||
this.refresh_wifi_state(conn, &network_manager).await?;
|
||||
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
pub async fn refresh_wifi_state(
|
||||
&mut self,
|
||||
conn: &zbus::Connection,
|
||||
network_manager: &NetworkManager<'_>,
|
||||
) -> Result<(), Error> {
|
||||
let (airplane_mode, wireless_enabled, settings_res) = futures::join!(
|
||||
Command::new("rfkill")
|
||||
.arg("list")
|
||||
.arg("bluetooth")
|
||||
.output()
|
||||
.then(|res| async move {
|
||||
let Ok(output) = res else {
|
||||
return false;
|
||||
};
|
||||
|
||||
std::str::from_utf8(&output.stdout)
|
||||
.ok()
|
||||
.map_or(false, |stdout| stdout.contains("Soft blocked: yes"))
|
||||
}),
|
||||
network_manager
|
||||
.wireless_enabled()
|
||||
.then(|res| async move { res.unwrap_or_default() }),
|
||||
NetworkManagerSettings::new(conn)
|
||||
);
|
||||
|
||||
self.wifi_enabled = wireless_enabled;
|
||||
self.airplane_mode = airplane_mode && !self.wifi_enabled;
|
||||
|
||||
let settings = settings_res?;
|
||||
|
||||
_ = settings.load_connections(&[]).await;
|
||||
|
||||
let (known_conns, active_conns, devices, connectivity) = futures::join!(
|
||||
settings.list_connections(),
|
||||
network_manager.active_connections(),
|
||||
network_manager.devices(),
|
||||
network_manager.connectivity(),
|
||||
);
|
||||
|
||||
let devices = devices.unwrap_or_default();
|
||||
let known_conns = known_conns.unwrap_or_default();
|
||||
|
||||
let (active_conns, wireless_access_points) = futures::join!(
|
||||
// Retrieve active connections.
|
||||
async move {
|
||||
let mut active_conns = active_connections(active_conns.unwrap_or_default())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
active_conns.sort_by(|a, b| {
|
||||
let helper = |conn: &ActiveConnectionInfo| match conn {
|
||||
ActiveConnectionInfo::Vpn { name, .. } => format!("0{name}"),
|
||||
ActiveConnectionInfo::Wired { name, .. } => format!("1{name}"),
|
||||
ActiveConnectionInfo::WiFi { name, .. } => format!("2{name}"),
|
||||
};
|
||||
helper(a).cmp(&helper(b))
|
||||
});
|
||||
|
||||
active_conns
|
||||
},
|
||||
// Retrieve all access points, and sort by strength.
|
||||
async move {
|
||||
let mut wireless_access_points = futures::stream::FuturesUnordered::from_iter(
|
||||
devices.iter().map(|device| async move {
|
||||
if let Ok(Some(SpecificDevice::Wireless(wireless_device))) =
|
||||
device.downcast_to_device().await
|
||||
{
|
||||
handle_wireless_device(wireless_device, device.hw_address().await.ok())
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}),
|
||||
)
|
||||
.fold(
|
||||
Vec::with_capacity(devices.len()),
|
||||
|mut access_points, mut f| async move {
|
||||
access_points.append(&mut f);
|
||||
access_points
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
wireless_access_points.sort_by(|a, b| b.strength.cmp(&a.strength));
|
||||
wireless_access_points
|
||||
}
|
||||
);
|
||||
|
||||
// Concurrently get
|
||||
let known_ssid: Vec<Arc<str>> = futures::stream::FuturesOrdered::from_iter(
|
||||
known_conns.into_iter().map(|c| async move {
|
||||
let s = c.get_settings().await.ok()?;
|
||||
let s = Settings::new(s);
|
||||
let curr_ssid = s
|
||||
.wifi
|
||||
.clone()
|
||||
.and_then(|w| w.ssid)
|
||||
.and_then(|ssid| String::from_utf8(ssid).ok())?;
|
||||
|
||||
Some(Arc::from(curr_ssid))
|
||||
}),
|
||||
)
|
||||
.filter_map(|c| async move { c })
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
self.known_access_points = wireless_access_points
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
known_ssid.contains(&a.ssid)
|
||||
&& !active_conns.iter().any(|ac| &ac.name() == a.ssid.as_ref())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
self.wireless_access_points = wireless_access_points;
|
||||
self.active_conns = active_conns;
|
||||
self.connectivity = connectivity?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn clear(&mut self) {
|
||||
self.active_conns = Vec::new();
|
||||
self.known_access_points = Vec::new();
|
||||
self.wireless_access_points = Vec::new();
|
||||
}
|
||||
|
||||
async fn connect_wifi<'a>(
|
||||
&self,
|
||||
conn: &zbus::Connection,
|
||||
ssid: &str,
|
||||
identity: Option<&str>,
|
||||
password: Option<&str>,
|
||||
hw_address: HwAddress,
|
||||
) -> Result<(), Error> {
|
||||
let nm = NetworkManager::new(conn).await?;
|
||||
|
||||
for c in nm.active_connections().await.unwrap_or_default() {
|
||||
if self
|
||||
.wireless_access_points
|
||||
.iter()
|
||||
.any(|w| Ok(Some(w.ssid.as_ref())) == c.cached_id().as_ref().map(|v| v.as_deref()))
|
||||
{
|
||||
_ = nm.deactivate_connection(&c).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let Some(ap) = self
|
||||
.wireless_access_points
|
||||
.iter()
|
||||
.find(|ap| ap.ssid.as_ref() == ssid && ap.hw_address == hw_address)
|
||||
else {
|
||||
return Err(Error::AccessPointNotFound);
|
||||
};
|
||||
|
||||
let mut conn_settings: HashMap<&str, HashMap<&str, zvariant::Value>> = HashMap::from([
|
||||
(
|
||||
"802-11-wireless",
|
||||
HashMap::from([("ssid", Value::Array(ssid.as_bytes().into()))]),
|
||||
),
|
||||
(
|
||||
"connection",
|
||||
HashMap::from([
|
||||
("id", Value::Str(ssid.into())),
|
||||
("type", Value::Str("802-11-wireless".into())),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
if let Some(identity) = identity {
|
||||
conn_settings.insert(
|
||||
"802-1x",
|
||||
HashMap::from([
|
||||
("identity", Value::Str(identity.into())),
|
||||
// most common default
|
||||
("eap", Value::Array(vec!["peap"].into())),
|
||||
// most common default
|
||||
("phase2-auth", Value::Str("mschapv2".into())),
|
||||
("password", Value::Str(password.unwrap_or("").into())),
|
||||
]),
|
||||
);
|
||||
let wireless = conn_settings.get_mut("802-11-wireless").unwrap();
|
||||
wireless.insert("security", Value::Str("802-11-wireless-security".into()));
|
||||
wireless.insert("mode", Value::Str("infrastructure".into()));
|
||||
conn_settings.insert(
|
||||
"802-11-wireless-security",
|
||||
HashMap::from([("key-mgmt", Value::Str("wpa-eap".into()))]),
|
||||
);
|
||||
} else if let Some(pass) = password {
|
||||
conn_settings.insert(
|
||||
"802-11-wireless-security",
|
||||
HashMap::from([
|
||||
("psk", Value::Str(pass.into())),
|
||||
("key-mgmt", Value::Str("wpa-psk".into())),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
let devices = nm.devices().await?;
|
||||
for device in devices {
|
||||
if !matches!(
|
||||
device.device_type().await.unwrap_or(DeviceType::Other),
|
||||
DeviceType::Wifi
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let s = NetworkManagerSettings::new(conn).await?;
|
||||
let known_conns = s.list_connections().await.unwrap_or_default();
|
||||
let mut known_conn = None;
|
||||
for c in known_conns {
|
||||
let settings = c.get_settings().await.ok().unwrap_or_default();
|
||||
|
||||
let s = Settings::new(settings);
|
||||
if let Some(cur_ssid) = s
|
||||
.wifi
|
||||
.clone()
|
||||
.and_then(|w| w.ssid)
|
||||
.and_then(|ssid| String::from_utf8(ssid).ok())
|
||||
{
|
||||
if cur_ssid == ssid {
|
||||
known_conn = Some(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let active_conn = if let Some(known_conn) = known_conn.as_ref() {
|
||||
// update settings if needed
|
||||
if password.is_some() {
|
||||
known_conn.update(conn_settings).await?;
|
||||
}
|
||||
|
||||
nm.activate_connection(known_conn, &device).await?
|
||||
} else {
|
||||
let (_, active_conn) = nm
|
||||
.add_and_activate_connection(conn_settings, device.inner().path(), &ap.path)
|
||||
.await?;
|
||||
let dummy = ActiveConnectionProxy::new(&conn, active_conn).await?;
|
||||
let active = ActiveConnectionProxy::builder(&conn)
|
||||
.destination(dummy.inner().destination().to_owned())
|
||||
.unwrap()
|
||||
.interface(dummy.inner().interface().to_owned())
|
||||
.unwrap()
|
||||
.path(dummy.inner().path().to_owned())
|
||||
.unwrap()
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
ActiveConnection::from(active)
|
||||
};
|
||||
let mut changes = active_conn.receive_state_changed().await;
|
||||
_ = tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
|
||||
let mut count = 5;
|
||||
loop {
|
||||
let state = active_conn.state().await;
|
||||
if let Ok(enums::ActiveConnectionState::Activated) = state {
|
||||
return Ok(());
|
||||
} else if let Ok(enums::ActiveConnectionState::Deactivated) = state {
|
||||
return Err(Error::ConnectionActivate);
|
||||
}
|
||||
match tokio::time::timeout(Duration::from_secs(20), changes.next()).await {
|
||||
Ok(Some(s)) => {
|
||||
let state = s.get().await.unwrap_or_default().into();
|
||||
if matches!(state, enums::ActiveConnectionState::Activated) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
count -= 1;
|
||||
if count <= 0 {
|
||||
return Err(Error::ConnectionActivate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::NoWiFiDevices)
|
||||
}
|
||||
}
|
||||
63
subscriptions/network-manager/src/wireless_enabled.rs
Normal file
63
subscriptions/network-manager/src/wireless_enabled.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// Copyright 2024 System76 <info@system76.com>
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
use super::Event;
|
||||
use cosmic_dbus_networkmanager::nm::NetworkManager;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use iced_futures::{Subscription, stream};
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
use zbus::Connection;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum State {
|
||||
Continue(Connection),
|
||||
Error,
|
||||
}
|
||||
|
||||
pub fn wireless_enabled_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
|
||||
id: I,
|
||||
conn: Connection,
|
||||
) -> iced_futures::Subscription<Event> {
|
||||
Subscription::run_with_id(
|
||||
id,
|
||||
stream::channel(50, move |output| async move {
|
||||
watch(conn, output).await;
|
||||
futures::future::pending().await
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn watch(conn: zbus::Connection, mut output: futures::channel::mpsc::Sender<Event>) {
|
||||
let mut state = State::Continue(conn);
|
||||
|
||||
loop {
|
||||
state = start_listening(state, &mut output).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_listening(
|
||||
state: State,
|
||||
output: &mut futures::channel::mpsc::Sender<Event>,
|
||||
) -> State {
|
||||
let conn = match state {
|
||||
State::Continue(conn) => conn,
|
||||
State::Error => futures::future::pending().await,
|
||||
};
|
||||
|
||||
let network_manager = match NetworkManager::new(&conn).await {
|
||||
Ok(n) => n,
|
||||
Err(why) => {
|
||||
tracing::error!(why = why.to_string(), "Failed to connect to NetworkManager");
|
||||
return State::Error;
|
||||
}
|
||||
};
|
||||
|
||||
let mut wireless_enabled_changed = network_manager.receive_wireless_enabled_changed().await;
|
||||
|
||||
while let Some(change) = wireless_enabled_changed.next().await {
|
||||
if let Ok(enable) = change.get().await {
|
||||
_ = output.send(Event::WiFiEnabled(enable)).await;
|
||||
}
|
||||
}
|
||||
State::Continue(conn)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue