mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 21:06:09 +00:00
Expose Android Wi-Fi names and nearby networks to Steam
This commit is contained in:
1 parent
0816562065
commit
5614621d6e
4 files changed
+238
-32
No files matched your search
@@ -13,6 +13,10 @@
|
||||
download from being throttled to nothing by the radio's power-save. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<!-- Local Wi-Fi discovery experiment: Android gates SSIDs and scan results on Location. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<!-- Ends background processes of another app that holds the Steam login. GameHub starts
|
||||
itself with the phone via boot receivers and signs this client out seconds after every
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.Manifest
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.LocationManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
@@ -8,6 +14,9 @@ import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
@@ -42,6 +51,21 @@ class LinuxNetworkLinkComponent(
|
||||
private var currentNetwork: Network? = null
|
||||
private var currentProperties: LinkProperties? = null
|
||||
private var currentCapabilities: NetworkCapabilities? = null
|
||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
private val scanHandler = Handler(Looper.getMainLooper())
|
||||
private var wifiReceiver: BroadcastReceiver? = null
|
||||
private var scanRequestStamp = 0L
|
||||
private var lastScanRequest = -SCAN_INTERVAL_MS
|
||||
private val scanRequests = object : Runnable {
|
||||
override fun run() {
|
||||
val stamp = File(rootDir, "etc/bannerlator-wifi-scan-request").lastModified()
|
||||
if (stamp != 0L && stamp != scanRequestStamp) {
|
||||
scanRequestStamp = stamp
|
||||
requestWifiScan()
|
||||
}
|
||||
if (wifiReceiver != null) scanHandler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called before the session starts, so its first process already sees the link. */
|
||||
fun publish() = synchronized(lock) {
|
||||
@@ -85,9 +109,28 @@ class LinuxNetworkLinkComponent(
|
||||
}
|
||||
synchronized(lock) { callback = registered }
|
||||
connectivity.registerDefaultNetworkCallback(registered)
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
}
|
||||
}
|
||||
wifiReceiver = receiver
|
||||
appContext.registerReceiver(receiver, IntentFilter().apply {
|
||||
addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
|
||||
addAction(WifiManager.RSSI_CHANGED_ACTION)
|
||||
addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
|
||||
addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
|
||||
addAction(LocationManager.MODE_CHANGED_ACTION)
|
||||
})
|
||||
scanRequestStamp = File(rootDir, "etc/bannerlator-wifi-scan-request").lastModified()
|
||||
scanHandler.post(scanRequests)
|
||||
requestWifiScan()
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
scanHandler.removeCallbacks(scanRequests)
|
||||
wifiReceiver?.let { appContext.unregisterReceiver(it) }
|
||||
wifiReceiver = null
|
||||
val registered = synchronized(lock) { callback.also { callback = null } } ?: return
|
||||
try {
|
||||
connectivity.unregisterNetworkCallback(registered)
|
||||
@@ -96,6 +139,26 @@ class LinuxNetworkLinkComponent(
|
||||
}
|
||||
}
|
||||
|
||||
private fun canReadWifiNames(): Boolean {
|
||||
val allowed = listOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
.any { appContext.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
|
||||
val location = appContext.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
return allowed && (Build.VERSION.SDK_INT < Build.VERSION_CODES.P || location?.isLocationEnabled == true)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun requestWifiScan() {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (!canReadWifiNames() || wifiManager?.isWifiEnabled != true || now - lastScanRequest < SCAN_INTERVAL_MS) return
|
||||
lastScanRequest = now
|
||||
try {
|
||||
Log.i(TAG, "Wi-Fi scan requested: accepted=${wifiManager.startScan()}")
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Wi-Fi scan permission unavailable")
|
||||
}
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
}
|
||||
|
||||
private fun write(properties: LinkProperties?, capabilities: NetworkCapabilities?) {
|
||||
val file = File(rootDir, LINK_FILE)
|
||||
synchronized(lock) {
|
||||
@@ -115,7 +178,10 @@ class LinuxNetworkLinkComponent(
|
||||
/** NetworkManager's view of Android. Kept separate from netif.c's legacy adapter format. */
|
||||
@Suppress("DEPRECATION")
|
||||
private fun writeNetworkState(properties: LinkProperties?, capabilities: NetworkCapabilities?) {
|
||||
val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
val namesAllowed = canReadWifiNames()
|
||||
val scans = if (namesAllowed && wifiManager?.isWifiEnabled == true) {
|
||||
try { wifiManager.scanResults.orEmpty() } catch (e: SecurityException) { emptyList() }
|
||||
} else emptyList()
|
||||
val transport = when {
|
||||
capabilities == null -> "none"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "wifi"
|
||||
@@ -133,6 +199,20 @@ class LinuxNetworkLinkComponent(
|
||||
put("captivePortal", capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL) == true)
|
||||
put("metered", capabilities?.let { !it.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) })
|
||||
put("wifiEnabled", wifiManager?.isWifiEnabled == true)
|
||||
put("scanAllowed", namesAllowed)
|
||||
put("lastScan", scans.maxOfOrNull { it.timestamp / 1000 } ?: -1L)
|
||||
put("accessPoints", JSONArray().apply {
|
||||
scans.filter { it.SSID.isNotEmpty() }.forEach {
|
||||
put(JSONObject().apply {
|
||||
put("ssid", it.SSID)
|
||||
put("bssid", it.BSSID)
|
||||
put("strength", WifiManager.calculateSignalLevel(it.level, 101))
|
||||
put("frequency", it.frequency)
|
||||
put("capabilities", it.capabilities)
|
||||
put("lastSeen", it.timestamp / 1_000_000)
|
||||
})
|
||||
}
|
||||
})
|
||||
put("addresses", JSONArray().apply {
|
||||
properties?.linkAddresses.orEmpty().forEach {
|
||||
put(JSONObject().put("address", it.address.hostAddress?.substringBefore('%')).put("prefix", it.prefixLength))
|
||||
@@ -159,8 +239,10 @@ class LinuxNetworkLinkComponent(
|
||||
if (info != null) {
|
||||
// SSIDs can be redacted by Android. No location permission is needed to
|
||||
// report the transport; a hidden name simply displays as Wi-Fi in Steam.
|
||||
info.ssid?.takeUnless { it == WifiManager.UNKNOWN_SSID || it.isEmpty() }
|
||||
val namedInfo = if (namesAllowed) wifiManager?.connectionInfo ?: info else info
|
||||
namedInfo.ssid?.takeUnless { it == WifiManager.UNKNOWN_SSID || it.isEmpty() }
|
||||
?.removeSurrounding("\"")?.let { put("ssid", it) }
|
||||
namedInfo.bssid?.takeUnless { it == "02:00:00:00:00:00" }?.let { put("bssid", it) }
|
||||
put("strength", WifiManager.calculateSignalLevel(info.rssi, 101))
|
||||
put("frequency", info.frequency.coerceAtLeast(0))
|
||||
put("bitrate", info.linkSpeed.coerceAtLeast(0) * 1000)
|
||||
@@ -255,5 +337,6 @@ class LinuxNetworkLinkComponent(
|
||||
private const val DEFAULT_MTU = 1500
|
||||
private const val OFFLINE_NAME = "eth0"
|
||||
private const val OFFLINE_ADDRESS = "10.0.0.2 24"
|
||||
private const val SCAN_INTERVAL_MS = 30_000L
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
#!/usr/bin/python3
|
||||
# Based on WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0.
|
||||
# Steam speaks NetworkManager; Android owns the radios, routes and connection. Export the
|
||||
# app's live snapshot through that API, including the connected Wi-Fi access point. Android
|
||||
# settings still handle scanning/joining networks; this service never changes the host link.
|
||||
# app's live snapshot through that API, including nearby Wi-Fi access points. Requests to
|
||||
# scan are handed to Android; Android settings still handle joining networks.
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
@@ -26,6 +28,7 @@ AP = ROOT + "/AccessPoint/1"
|
||||
PROFILE = SETTINGS + "/1"
|
||||
UUID = "b1d0c8e4-57f0-4c0e-9d60-77696e6e6174"
|
||||
SNAPSHOT = Path("/etc/bannerlator-network.json")
|
||||
SCAN_REQUEST = Path("/etc/bannerlator-wifi-scan-request")
|
||||
OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
|
||||
PROPERTIES = "org.freedesktop.DBus.Properties"
|
||||
|
||||
@@ -141,8 +144,67 @@ def ip_config(state, version):
|
||||
return props
|
||||
|
||||
|
||||
def ap_path(bssid):
|
||||
if bssid and re.fullmatch(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}", bssid):
|
||||
return ROOT + "/AccessPoint/" + bssid.replace(":", "").lower()
|
||||
return AP
|
||||
|
||||
|
||||
def active_ap(state):
|
||||
return ap_path(state.get("bssid")) if state["connected"] and state.get("transport") == "wifi" else "/"
|
||||
|
||||
|
||||
def ap_security(capabilities):
|
||||
# NetworkManager's cipher/key-management flags, from Android's beacon capabilities.
|
||||
wpa = rsn = 0
|
||||
for group in re.findall(r"\[([^]]+)\]", capabilities.upper()):
|
||||
flags = 0
|
||||
if "CCMP" in group:
|
||||
flags |= 0x08 | 0x80
|
||||
if "TKIP" in group:
|
||||
flags |= 0x04 | 0x40
|
||||
if "PSK" in group:
|
||||
flags |= 0x100
|
||||
if "EAP" in group:
|
||||
flags |= 0x200
|
||||
if "SAE" in group:
|
||||
flags |= 0x400
|
||||
if "OWE" in group:
|
||||
flags |= 0x800
|
||||
if "WPA2" in group or "RSN" in group or "SAE" in group or "OWE" in group:
|
||||
rsn |= flags
|
||||
elif "WPA" in group:
|
||||
wpa |= flags
|
||||
privacy = int(bool(wpa or rsn or "WEP" in capabilities.upper()))
|
||||
return privacy, wpa, rsn
|
||||
|
||||
|
||||
def access_points(state):
|
||||
result = {ap_path(ap.get("bssid")): dict(ap) for ap in state.get("accessPoints", []) if ap.get("ssid")}
|
||||
if active_ap(state) != "/":
|
||||
current = result.setdefault(active_ap(state), {})
|
||||
for key in ("ssid", "bssid", "strength", "frequency", "bitrate"):
|
||||
if key in state:
|
||||
current[key] = state[key]
|
||||
current.setdefault("ssid", "Wi-Fi")
|
||||
return result
|
||||
|
||||
|
||||
def ap_properties(ap):
|
||||
privacy, wpa, rsn = ap_security(ap.get("capabilities", ""))
|
||||
return {
|
||||
"Flags": v("u", privacy), "WpaFlags": v("u", wpa), "RsnFlags": v("u", rsn),
|
||||
"Ssid": v("ay", list(ap["ssid"].encode("utf-8"))),
|
||||
"Frequency": v("u", ap.get("frequency", 0)), "HwAddress": v("s", ap.get("bssid", "")), "Mode": v("u", 2),
|
||||
"MaxBitrate": v("u", ap.get("bitrate", 0)),
|
||||
"Strength": v("y", max(0, min(100, ap.get("strength", 0)))), "LastSeen": v("i", ap.get("lastSeen", -1)),
|
||||
}
|
||||
|
||||
|
||||
def objects(state):
|
||||
device = device_path(state)
|
||||
aps = access_points(state)
|
||||
current_ap = active_ap(state)
|
||||
up = state["connected"]
|
||||
transport = state.get("transport", "none")
|
||||
wifi = transport == "wifi" or (not up and state.get("wifiEnabled", False))
|
||||
@@ -191,17 +253,11 @@ def objects(state):
|
||||
found[device][NAME + ".Device.Wireless"] = {
|
||||
"HwAddress": v("s", ""), "PermHwAddress": v("s", ""), "Mode": v("u", 2),
|
||||
"Bitrate": v("u", state.get("bitrate", 0)), "WirelessCapabilities": v("u", 0),
|
||||
"AccessPoints": v("ao", [AP] if up else []), "ActiveAccessPoint": v("o", AP if up else "/"),
|
||||
"LastScan": v("x", -1),
|
||||
"AccessPoints": v("ao", list(aps)), "ActiveAccessPoint": v("o", current_ap),
|
||||
"LastScan": v("x", state.get("lastScan", -1)),
|
||||
}
|
||||
if up:
|
||||
found[AP] = {NAME + ".AccessPoint": {
|
||||
"Flags": v("u", 0), "WpaFlags": v("u", 0), "RsnFlags": v("u", 0),
|
||||
"Ssid": v("ay", list((state.get("ssid") or "Wi-Fi").encode("utf-8"))),
|
||||
"Frequency": v("u", state.get("frequency", 0)), "HwAddress": v("s", ""), "Mode": v("u", 2),
|
||||
"MaxBitrate": v("u", state.get("bitrate", 0)),
|
||||
"Strength": v("y", max(0, min(100, state.get("strength", 0)))), "LastSeen": v("i", -1),
|
||||
}}
|
||||
for path, ap in aps.items():
|
||||
found[path] = {NAME + ".AccessPoint": ap_properties(ap)}
|
||||
elif cellular:
|
||||
found[device][NAME + ".Device.Modem"] = {
|
||||
"ModemCapabilities": v("u", 4), "CurrentCapabilities": v("u", 4),
|
||||
@@ -213,7 +269,7 @@ def objects(state):
|
||||
}
|
||||
if up:
|
||||
found[ACTIVE] = {NAME + ".Connection.Active": {
|
||||
"Connection": v("o", PROFILE), "SpecificObject": v("o", AP if wifi else "/"),
|
||||
"Connection": v("o", PROFILE), "SpecificObject": v("o", current_ap),
|
||||
"Id": v("s", connection_name(state)), "Uuid": v("s", UUID), "Type": v("s", kind),
|
||||
"Devices": v("ao", [device]), "State": v("u", 2), "StateFlags": v("u", 0),
|
||||
"Default": v("b", ip4), "Default6": v("b", ip6),
|
||||
@@ -223,6 +279,18 @@ def objects(state):
|
||||
for version, present, path in ((4, ip4, IP4), (6, ip6, IP6)):
|
||||
if present:
|
||||
found[path] = {NAME + f".IP{version}Config": ip_config(state, version)}
|
||||
if up and not wifi and state.get("wifiEnabled"):
|
||||
# Android can keep its Wi-Fi radio available while cellular/VPN is the default route.
|
||||
wireless = objects(dict(state, connected=False, transport="none",
|
||||
interface=state.get("wifiInterface", "wlan0"), metered=None))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
found[wifi_device] = wireless[wifi_device]
|
||||
found[wifi_device][NAME + ".Device"]["AvailableConnections"] = v("ao", [])
|
||||
for path, interfaces in wireless.items():
|
||||
if NAME + ".AccessPoint" in interfaces:
|
||||
found[path] = interfaces
|
||||
found[ROOT][NAME]["Devices"] = v("ao", [device, wifi_device])
|
||||
found[ROOT][NAME]["AllDevices"] = v("ao", [device, wifi_device])
|
||||
return found
|
||||
|
||||
|
||||
@@ -284,14 +352,20 @@ class NetworkManager:
|
||||
elif method == "ListConnections":
|
||||
invocation.return_value(v("(ao)", ([PROFILE],)))
|
||||
elif method in ("GetAccessPoints", "GetAllAccessPoints"):
|
||||
invocation.return_value(v("(ao)", ([AP] if AP in self.objects else [],)))
|
||||
invocation.return_value(v("(ao)", (self.objects[path][NAME + ".Device.Wireless"]["AccessPoints"].unpack(),)))
|
||||
elif method == "RequestScan":
|
||||
# Only the AP Android is already using is available. Refresh that view; do not
|
||||
# pretend to scan the host's radio or disrupt its connection.
|
||||
if self.state.get("scanAllowed") is False:
|
||||
invocation.return_dbus_error(NAME + ".Device.NotAllowed", "Wi-Fi discovery requires Android Location permission and enabled Location services")
|
||||
return
|
||||
try:
|
||||
SCAN_REQUEST.write_text(str(time.monotonic_ns()))
|
||||
except OSError:
|
||||
invocation.return_dbus_error(NAME + ".Device.Failed", "Could not request an Android Wi-Fi scan")
|
||||
return
|
||||
self.check()
|
||||
invocation.return_value(v("()", ()))
|
||||
elif method in ("GetDevices", "GetAllDevices"):
|
||||
invocation.return_value(v("(ao)", ([device_path(self.state)],)))
|
||||
invocation.return_value(v("(ao)", (self.objects[ROOT][NAME]["Devices"].unpack(),)))
|
||||
else:
|
||||
invocation.return_dbus_error(NAME + ".NotSupported", "Manage this connection in Android settings")
|
||||
|
||||
@@ -316,13 +390,15 @@ class NetworkManager:
|
||||
changed = {k: value for k, value in after[path][interface].items() if value != before[path][interface].get(k)}
|
||||
if changed:
|
||||
self.bus.emit_signal(None, path, PROPERTIES, "PropertiesChanged", v("(sa{sv}as)", (interface, changed, [])))
|
||||
was_ap, has_ap = AP in before, AP in after
|
||||
if was_ap != has_ap:
|
||||
# Wireless consumers subscribe to these as well as ObjectManager.
|
||||
device = device_path(state)
|
||||
if NAME + ".Device.Wireless" in after[device]:
|
||||
self.bus.emit_signal(None, device, NAME + ".Device.Wireless",
|
||||
"AccessPointAdded" if has_ap else "AccessPointRemoved", v("(o)", (AP,)))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
wireless = NAME + ".Device.Wireless"
|
||||
old_aps = before.get(wifi_device, {}).get(wireless, {}).get("AccessPoints", v("ao", [])).unpack()
|
||||
new_aps = after.get(wifi_device, {}).get(wireless, {}).get("AccessPoints", v("ao", [])).unpack()
|
||||
if wifi_device in after:
|
||||
for path in set(old_aps) - set(new_aps):
|
||||
self.bus.emit_signal(None, wifi_device, wireless, "AccessPointRemoved", v("(o)", (path,)))
|
||||
for path in set(new_aps) - set(old_aps):
|
||||
self.bus.emit_signal(None, wifi_device, wireless, "AccessPointAdded", v("(o)", (path,)))
|
||||
was = before[ROOT][NAME]["State"]
|
||||
now = after[ROOT][NAME]["State"]
|
||||
if now != was:
|
||||
|
||||
@@ -101,6 +101,27 @@ class NetworkObjectsTest(unittest.TestCase):
|
||||
self.assertEqual(found[nm.device_path(state)][nm.NAME + ".Device"]["DeviceType"].unpack(), device_type)
|
||||
self.assertNotIn(nm.AP, found)
|
||||
|
||||
def test_named_current_and_nearby_access_points(self):
|
||||
current = {"ssid": "Current Wi-Fi", "bssid": "00:11:22:33:44:55", "strength": 75,
|
||||
"capabilities": "[WPA2-PSK-CCMP][RSN-PSK+SAE-CCMP][ESS]"}
|
||||
other = {"ssid": "Other Wi-Fi", "bssid": "00:11:22:33:44:66", "strength": 42,
|
||||
"capabilities": "[ESS]"}
|
||||
state = dict(WIFI, ssid=current["ssid"], bssid=current["bssid"], accessPoints=[current, other], lastScan=123456)
|
||||
found = nm.objects(state)
|
||||
wireless = found[nm.device_path(state)][nm.NAME + ".Device.Wireless"]
|
||||
self.assertEqual(wireless["ActiveAccessPoint"].unpack(), nm.ap_path(current["bssid"]))
|
||||
self.assertEqual(set(wireless["AccessPoints"].unpack()), {nm.ap_path(current["bssid"]), nm.ap_path(other["bssid"])})
|
||||
self.assertEqual(wireless["LastScan"].unpack(), 123456)
|
||||
secured = found[nm.ap_path(current["bssid"])][nm.NAME + ".AccessPoint"]
|
||||
self.assertEqual(secured["Flags"].unpack(), 1)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x100)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x400)
|
||||
self.assertEqual(found[nm.ap_path(other["bssid"])][nm.NAME + ".AccessPoint"]["Flags"].unpack(), 0)
|
||||
# Keep nearby-network discovery while a cellular connection provides the default route.
|
||||
cellular = nm.objects(dict(CELLULAR, accessPoints=[other]))
|
||||
self.assertIn(nm.ap_path(other["bssid"]), cellular)
|
||||
self.assertEqual(cellular[nm.ROOT + "/Devices/Wifi"][nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), "/")
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class NetworkBusTest(unittest.TestCase):
|
||||
@@ -111,7 +132,7 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
# Use the production service and only redirect its input file for the fixture.
|
||||
launch = "import runpy,sys; from pathlib import Path; n=runpy.run_path(sys.argv[1]); n['main'].__globals__['SNAPSHOT']=Path(sys.argv[2]); n['main']()"
|
||||
launch = "import runpy,sys; from pathlib import Path; n=runpy.run_path(sys.argv[1]); g=n['main'].__globals__; g['SNAPSHOT']=Path(sys.argv[2]); g['SCAN_REQUEST']=Path(sys.argv[2]).with_suffix('.request'); n['main']()"
|
||||
self.process = subprocess.Popen([sys.executable, "-c", launch, str(SCRIPT), str(self.snapshot)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
self.await_type("802-11-wireless")
|
||||
@@ -171,16 +192,16 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
cell_path = nm.device_path(CELLULAR)
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "GetDevices"), ([cell_path],))
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "GetDevices"), ([cell_path, nm.ROOT + "/Devices/Wifi"],))
|
||||
self.assertEqual(self.prop(cell_path, nm.NAME + ".Device", "DeviceType"), 8)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "Metered"), 1)
|
||||
managed = self.call(nm.ROOT, nm.OBJECT_MANAGER, "GetManagedObjects")[0]
|
||||
self.assertNotIn(wifi_path, managed)
|
||||
self.assertIn(wifi_path, managed)
|
||||
self.assertEqual(managed[wifi_path][nm.NAME + ".Device"]["State"], 30)
|
||||
self.assertNotIn(nm.AP, managed)
|
||||
self.assertNotIn(nm.IP4, managed)
|
||||
self.assertIn(nm.IP6, managed)
|
||||
with self.assertRaises(GLib.Error):
|
||||
self.prop(wifi_path, nm.NAME + ".Device", "DeviceType")
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device.Wireless", "ActiveAccessPoint"), "/")
|
||||
self.write(OFFLINE)
|
||||
self.await_type("")
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "CheckConnectivity"), (1,))
|
||||
@@ -193,7 +214,7 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.assertTrue(any(interface == nm.PROPERTIES and member == "PropertiesChanged" and
|
||||
args[1].get("PrimaryConnectionType") == "gsm"
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(interface == nm.OBJECT_MANAGER and member == "InterfacesRemoved" and args[0] == wifi_path
|
||||
self.assertTrue(any(interface == nm.OBJECT_MANAGER and member == "InterfacesRemoved" and args[0] == nm.AP
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(member == "AccessPointAdded" for _, _, member, _ in signals))
|
||||
# A missing/invalid snapshot is a transient input error, never a fake Ethernet handover.
|
||||
@@ -201,6 +222,28 @@ class NetworkBusTest(unittest.TestCase):
|
||||
time.sleep(1.2)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType"), "802-11-wireless")
|
||||
|
||||
def test_scan_requests_and_live_results(self):
|
||||
wifi_path = nm.device_path(WIFI)
|
||||
self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},)))
|
||||
self.assertTrue(self.snapshot.with_suffix(".request").is_file())
|
||||
current = {"ssid": "Named Current", "bssid": "00:11:22:33:44:55", "capabilities": "[WPA2-PSK-CCMP]"}
|
||||
other = {"ssid": "Nearby", "bssid": "00:11:22:33:44:66", "strength": 37, "capabilities": "[ESS]"}
|
||||
self.write(dict(WIFI, ssid=current["ssid"], bssid=current["bssid"], accessPoints=[current, other], scanAllowed=True))
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
aps = self.call(wifi_path, nm.NAME + ".Device.Wireless", "GetAllAccessPoints")[0]
|
||||
if nm.ap_path(other["bssid"]) in aps:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
self.assertIn(nm.ap_path(other["bssid"]), aps)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device.Wireless", "ActiveAccessPoint"), nm.ap_path(current["bssid"]))
|
||||
self.assertEqual(bytes(self.prop(nm.ap_path(other["bssid"]), nm.NAME + ".AccessPoint", "Ssid")).decode(), "Nearby")
|
||||
self.assertEqual(self.call(nm.PROFILE, nm.NAME + ".Settings.Connection", "GetSettings")[0]["connection"]["id"], "Named Current")
|
||||
self.write(dict(WIFI, scanAllowed=False))
|
||||
time.sleep(1.2)
|
||||
with self.assertRaises(GLib.Error):
|
||||
self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},)))
|
||||
|
||||
def test_libnm_client(self):
|
||||
try:
|
||||
gi.require_version("NM", "1.0")
|
||||
|
||||
Reference in new issue
Block a user