mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
Merge remote-tracking branch 'org/main' into feat/x86-64-steam-client
This commit is contained in:
commit
a99843e326
24 files changed
+1393
-196
No files matched your search
@@ -120,6 +120,9 @@ docker run --rm --platform linux/amd64 \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libblfastpath.so"
|
||||
mkdir -p "$d/usr/local/bin"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/* Android text -> Gamescope's Xwayland selection. Gamescope's Wayland backend does not
|
||||
* relay the outer compositor's clipboard. libX11 is loaded from the guest at runtime;
|
||||
* the small stable Xlib ABI below keeps this helper independent of cross X11 headers.
|
||||
* The private host file is atomically replaced, never put in session logs. */
|
||||
#define _GNU_SOURCE
|
||||
#include <sys/inotify.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <signal.h>
|
||||
#include <poll.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
|
||||
typedef struct _XDisplay Display;
|
||||
typedef unsigned long Window, Atom, Time;
|
||||
typedef struct {
|
||||
int type; unsigned long serial; int send_event; Display *display;
|
||||
Window owner, requestor; Atom selection, target, property; Time time;
|
||||
} SelectionRequest;
|
||||
typedef struct {
|
||||
int type; unsigned long serial; int send_event; Display *display;
|
||||
Window requestor; Atom selection, target, property; Time time;
|
||||
} SelectionNotify;
|
||||
typedef union { int type; SelectionRequest request; SelectionNotify selection; long pad[24]; } Event;
|
||||
|
||||
#define API(ret, name, args) static ret (*name) args
|
||||
API(Display *, XOpenDisplay, (const char *));
|
||||
API(Window, XDefaultRootWindow, (Display *));
|
||||
API(Window, XCreateSimpleWindow, (Display *, Window, int, int, unsigned, unsigned, unsigned, unsigned long, unsigned long));
|
||||
API(Atom, XInternAtom, (Display *, const char *, int));
|
||||
API(int, XSetSelectionOwner, (Display *, Atom, Window, Time));
|
||||
API(Window, XGetSelectionOwner, (Display *, Atom));
|
||||
API(int, XChangeProperty, (Display *, Window, Atom, Atom, int, int, const unsigned char *, int));
|
||||
API(int, XSendEvent, (Display *, Window, int, long, Event *));
|
||||
API(int, XPending, (Display *));
|
||||
API(int, XNextEvent, (Display *, Event *));
|
||||
API(int, XFlush, (Display *));
|
||||
API(int, XConnectionNumber, (Display *));
|
||||
API(int, XCloseDisplay, (Display *));
|
||||
API(void *, XSetErrorHandler, (int (*)(Display *, void *)));
|
||||
|
||||
/* Stay below X11's normal maximum property request. Never paste a truncated command. */
|
||||
#define MAX_TEXT (64 * 1024)
|
||||
static int ignore_x_error(Display *d, void *event) { (void)d; (void)event; return 0; }
|
||||
|
||||
/* The host renames complete files into place. The inode distinguishes copying the same
|
||||
* text again after a guest program has taken ownership of the clipboard. */
|
||||
static int refresh(Display *d, Window w, Atom clipboard, const char *path,
|
||||
char **text, size_t *len, ino_t *inode) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
if (fd < 0) return 0;
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_ino == *inode) { close(fd); return 0; }
|
||||
*inode = st.st_ino;
|
||||
if (st.st_size < 0 || st.st_size > MAX_TEXT) {
|
||||
fprintf(stderr, "== clipboard: text exceeds %d bytes, not pasted\n", MAX_TEXT);
|
||||
if (XGetSelectionOwner(d, clipboard) == w) XSetSelectionOwner(d, clipboard, 0, 0);
|
||||
XFlush(d);
|
||||
free(*text); *text = NULL; *len = 0;
|
||||
close(fd); return 0;
|
||||
}
|
||||
char *copy = malloc((size_t)st.st_size + 1);
|
||||
if (!copy) { close(fd); return 0; }
|
||||
size_t got = 0;
|
||||
while (got < (size_t)st.st_size) {
|
||||
ssize_t n = read(fd, copy + got, (size_t)st.st_size - got);
|
||||
if (n > 0) got += n;
|
||||
else if (n < 0 && errno == EINTR) continue;
|
||||
else break;
|
||||
}
|
||||
close(fd);
|
||||
if (got != (size_t)st.st_size) { free(copy); return 0; }
|
||||
copy[got] = 0;
|
||||
free(*text); *text = copy; *len = got;
|
||||
if (got) XSetSelectionOwner(d, clipboard, w, 0);
|
||||
else if (XGetSelectionOwner(d, clipboard) == w) XSetSelectionOwner(d, clipboard, 0, 0);
|
||||
XFlush(d);
|
||||
fprintf(stderr, "== clipboard: Android text available in Xwayland (%zu bytes)\n", got);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2 || !getenv("DISPLAY")) return 1;
|
||||
pid_t parent_pid = getppid();
|
||||
if (parent_pid == 1 || prctl(PR_SET_PDEATHSIG, SIGTERM) || getppid() != parent_pid) return 1;
|
||||
void *lib = dlopen("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!lib) { fprintf(stderr, "== clipboard: libX11 unavailable\n"); return 1; }
|
||||
#define LOAD(name) do { *(void **)(&name) = dlsym(lib, #name); if (!name) return 1; } while (0)
|
||||
LOAD(XOpenDisplay); LOAD(XDefaultRootWindow); LOAD(XCreateSimpleWindow); LOAD(XInternAtom);
|
||||
LOAD(XSetSelectionOwner); LOAD(XGetSelectionOwner); LOAD(XChangeProperty); LOAD(XSendEvent);
|
||||
LOAD(XPending); LOAD(XNextEvent); LOAD(XFlush); LOAD(XConnectionNumber); LOAD(XCloseDisplay);
|
||||
LOAD(XSetErrorHandler);
|
||||
Display *d = XOpenDisplay(NULL);
|
||||
if (!d) { fprintf(stderr, "== clipboard: cannot open Xwayland\n"); return 1; }
|
||||
XSetErrorHandler(ignore_x_error); /* A paste requester can close its window at any time. */
|
||||
Window w = XCreateSimpleWindow(d, XDefaultRootWindow(d), 0, 0, 1, 1, 0, 0, 0);
|
||||
Atom clipboard = XInternAtom(d, "CLIPBOARD", 0);
|
||||
Atom targets = XInternAtom(d, "TARGETS", 0), utf8 = XInternAtom(d, "UTF8_STRING", 0);
|
||||
Atom plain = XInternAtom(d, "text/plain;charset=utf-8", 0), text_atom = XInternAtom(d, "TEXT", 0);
|
||||
Atom string = XInternAtom(d, "STRING", 0);
|
||||
char parent[PATH_MAX];
|
||||
if (strlen(argv[1]) >= sizeof(parent)) return 1;
|
||||
strcpy(parent, argv[1]); char *slash = strrchr(parent, '/');
|
||||
if (!slash) return 1;
|
||||
*slash = 0;
|
||||
int watch = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
|
||||
if (watch < 0 || inotify_add_watch(watch, parent, IN_MOVED_TO | IN_CLOSE_WRITE) < 0) return 1;
|
||||
char *text = NULL; size_t len = 0; ino_t inode = 0;
|
||||
refresh(d, w, clipboard, argv[1], &text, &len, &inode);
|
||||
struct pollfd fds[] = {{XConnectionNumber(d), POLLIN, 0}, {watch, POLLIN, 0}};
|
||||
for (;;) {
|
||||
while (XPending(d)) {
|
||||
Event e; XNextEvent(d, &e);
|
||||
if (e.type != 30) continue; /* SelectionRequest */
|
||||
SelectionRequest *r = &e.request;
|
||||
Atom property = r->property ? r->property : r->target;
|
||||
Event reply = {0};
|
||||
reply.selection = (SelectionNotify){31, 0, 1, d, r->requestor, r->selection, r->target, 0, r->time};
|
||||
if (r->selection == clipboard && text && len) {
|
||||
size_t ascii; for (ascii = 0; ascii < len && (unsigned char)text[ascii] < 128; ascii++) {}
|
||||
if (r->target == targets) {
|
||||
Atom supported[] = {targets, utf8, plain, text_atom, string};
|
||||
XChangeProperty(d, r->requestor, property, 4 /* XA_ATOM */, 32, 0,
|
||||
(const unsigned char *)supported, ascii == len ? 5 : 4);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == utf8 || r->target == plain || r->target == text_atom) {
|
||||
XChangeProperty(d, r->requestor, property, utf8, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == string) {
|
||||
/* STRING is Latin-1. Offer it only for ASCII rather than corrupt UTF-8. */
|
||||
if (ascii == len) {
|
||||
XChangeProperty(d, r->requestor, property, string, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
}
|
||||
}
|
||||
}
|
||||
XSendEvent(d, r->requestor, 0, 0, &reply); XFlush(d);
|
||||
}
|
||||
if (poll(fds, 2, -1) < 0) { if (errno == EINTR) continue; break; }
|
||||
if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) break;
|
||||
if (fds[1].revents & POLLIN) {
|
||||
char events[4096]; while (read(watch, events, sizeof(events)) > 0) {}
|
||||
refresh(d, w, clipboard, argv[1], &text, &len, &inode);
|
||||
}
|
||||
}
|
||||
free(text); close(watch); XCloseDisplay(d); dlclose(lib);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,20 +1,17 @@
|
||||
#!/usr/bin/python3
|
||||
# Ported from WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0, with thanks.
|
||||
# Renamed again for this app; the answers themselves are his.
|
||||
#
|
||||
# Answers for NetworkManager on the runtime's system bus, for the Steam client:
|
||||
# bannerlator-netmanager
|
||||
#
|
||||
# The client's network page and its connection indicator are built on NetworkManager. It asks for
|
||||
# one over the system bus as it starts, and without an answer it leaves out half of what its
|
||||
# interface then calls: Settings > Internet stops with "StartScanningForNetworks is not a function"
|
||||
# and the header shows no connection while downloads run.
|
||||
#
|
||||
# The network here is Android's: the app has no say in Wi-Fi, and nothing in this runtime could
|
||||
# scan or join one. So this reports what is true and no more - one connection that is up while
|
||||
# Android has a route out, under the address the app was given - and refuses what it cannot do.
|
||||
# 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 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
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
import gi
|
||||
|
||||
@@ -24,207 +21,401 @@ from gi.repository import Gio, GLib # noqa: E402
|
||||
NAME = "org.freedesktop.NetworkManager"
|
||||
ROOT = "/org/freedesktop/NetworkManager"
|
||||
SETTINGS = ROOT + "/Settings"
|
||||
DEVICE = ROOT + "/Devices/1"
|
||||
ACTIVE = ROOT + "/ActiveConnection/1"
|
||||
IP4 = ROOT + "/IP4Config/1"
|
||||
IP6 = ROOT + "/IP6Config/1"
|
||||
AP = ROOT + "/AccessPoint/1"
|
||||
PROFILE = SETTINGS + "/1"
|
||||
UUID = "b1d0c8e4-57f0-4c0e-9d60-77696e6e6174"
|
||||
CHECK_SECONDS = 10
|
||||
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"
|
||||
|
||||
# NetworkManager's own numbers.
|
||||
NM_STATE_DISCONNECTED, NM_STATE_CONNECTED_GLOBAL = 20, 70
|
||||
NM_CONNECTIVITY_NONE, NM_CONNECTIVITY_FULL = 1, 4
|
||||
NM_DEVICE_TYPE_ETHERNET = 1
|
||||
NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_ACTIVATED = 30, 100
|
||||
NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2
|
||||
|
||||
INTROSPECTION = """
|
||||
<node>
|
||||
<interface name="org.freedesktop.DBus.ObjectManager">
|
||||
<method name="GetManagedObjects">
|
||||
<arg type="a{oa{sa{sv}}}" direction="out"/>
|
||||
</method>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager">
|
||||
<method name="GetPermissions"><arg type="a{ss}" direction="out"/></method>
|
||||
<method name="CheckConnectivity"><arg type="u" direction="out"/></method>
|
||||
<method name="GetDevices"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllDevices"><arg type="ao" direction="out"/></method>
|
||||
<signal name="StateChanged"><arg type="u"/></signal>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager.Settings.Connection">
|
||||
<method name="GetSettings"><arg type="a{sa{sv}}" direction="out"/></method>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager.Device">
|
||||
<signal name="StateChanged"><arg type="u"/><arg type="u"/><arg type="u"/></signal>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
|
||||
def address():
|
||||
"""The address Android routes out by, or None without a route. Nothing is sent."""
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("192.0.2.1", 9))
|
||||
return s.getsockname()[0]
|
||||
except OSError:
|
||||
return None
|
||||
METHODS = {
|
||||
OBJECT_MANAGER: '''
|
||||
<method name="GetManagedObjects"><arg type="a{oa{sa{sv}}}" direction="out"/></method>
|
||||
<signal name="InterfacesAdded"><arg type="o"/><arg type="a{sa{sv}}"/></signal>
|
||||
<signal name="InterfacesRemoved"><arg type="o"/><arg type="as"/></signal>''',
|
||||
NAME: '''
|
||||
<method name="GetPermissions"><arg type="a{ss}" direction="out"/></method>
|
||||
<method name="CheckConnectivity"><arg type="u" direction="out"/></method>
|
||||
<method name="GetDevices"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllDevices"><arg type="ao" direction="out"/></method>
|
||||
<signal name="StateChanged"><arg type="u"/></signal>''',
|
||||
NAME + ".Settings": '<method name="ListConnections"><arg type="ao" direction="out"/></method>',
|
||||
NAME + ".Settings.Connection": '<method name="GetSettings"><arg type="a{sa{sv}}" direction="out"/></method><signal name="Updated"/>',
|
||||
NAME + ".Device": '<signal name="StateChanged"><arg type="u"/><arg type="u"/><arg type="u"/></signal>',
|
||||
NAME + ".Device.Wireless": '''
|
||||
<method name="GetAccessPoints"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllAccessPoints"><arg type="ao" direction="out"/></method>
|
||||
<method name="RequestScan"><arg type="a{sv}" direction="in"/></method>
|
||||
<signal name="AccessPointAdded"><arg type="o"/></signal>
|
||||
<signal name="AccessPointRemoved"><arg type="o"/></signal>''',
|
||||
}
|
||||
|
||||
|
||||
def v(signature, value):
|
||||
return GLib.Variant(signature, value)
|
||||
|
||||
|
||||
def objects(ip):
|
||||
"""Every object NetworkManager would export, as its ObjectManager describes them."""
|
||||
up = ip is not None
|
||||
def read_snapshot():
|
||||
# Atomic replacement by the app means we never see a partially written handover.
|
||||
try:
|
||||
state = json.loads(SNAPSHOT.read_text())
|
||||
if not isinstance(state, dict) or not isinstance(state.get("connected"), bool):
|
||||
return None
|
||||
return state
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def legacy_snapshot():
|
||||
# Older APKs do not publish transport metadata. Never guess Wi-Fi from an interface name.
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.connect(("192.0.2.1", 9))
|
||||
ip = sock.getsockname()[0]
|
||||
return {"connected": True, "transport": "ethernet", "addresses": [{"address": ip, "prefix": 32}]}
|
||||
except OSError:
|
||||
return {"connected": False, "transport": "none"}
|
||||
|
||||
|
||||
def connection_type(state):
|
||||
return {"wifi": "802-11-wireless", "cellular": "gsm", "ethernet": "802-3-ethernet",
|
||||
"vpn": "tun"}.get(state.get("transport"), "generic")
|
||||
|
||||
|
||||
def device_path(state):
|
||||
transport = state.get("transport", "none")
|
||||
if not state["connected"] and state.get("wifiEnabled"):
|
||||
transport = "wifi"
|
||||
return ROOT + "/Devices/" + {"wifi": "Wifi", "cellular": "Cellular", "ethernet": "Ethernet",
|
||||
"vpn": "Vpn"}.get(transport, "Android")
|
||||
|
||||
|
||||
def connection_name(state):
|
||||
return {"wifi": state.get("ssid") or "Wi-Fi", "cellular": "Cellular", "ethernet": "Ethernet",
|
||||
"vpn": "VPN"}.get(state.get("transport"), "Android")
|
||||
|
||||
|
||||
def connectivity(state):
|
||||
if not state["connected"]:
|
||||
return 1 # NONE
|
||||
if state.get("validated"):
|
||||
return 4 # FULL
|
||||
return 2 if state.get("captivePortal") else 3 # PORTAL / LIMITED
|
||||
|
||||
|
||||
def metered(state):
|
||||
return {True: 1, False: 2}.get(state.get("metered"), 0)
|
||||
|
||||
|
||||
def family_addresses(state, version):
|
||||
return [entry for entry in state.get("addresses", [])
|
||||
if ipaddress.ip_address(entry["address"]).version == version]
|
||||
|
||||
|
||||
def ip_config(state, version):
|
||||
entries = family_addresses(state, version)
|
||||
gateways = [ip for ip in state.get("gateways", []) if ipaddress.ip_address(ip).version == version]
|
||||
dns = [ip for ip in state.get("dns", []) if ipaddress.ip_address(ip).version == version]
|
||||
gateway = gateways[0] if gateways else ""
|
||||
props = {
|
||||
"AddressData": v("aa{sv}", [{"address": v("s", a["address"]), "prefix": v("u", a["prefix"])} for a in entries]),
|
||||
"Gateway": v("s", gateway), "RouteData": v("aa{sv}", []),
|
||||
"Domains": v("as", []), "Searches": v("as", []), "DnsOptions": v("as", []), "DnsPriority": v("i", 0),
|
||||
}
|
||||
if version == 4:
|
||||
native = lambda ip: struct.unpack("=I", socket.inet_aton(ip))[0]
|
||||
props.update({
|
||||
"Addresses": v("aau", [[native(a["address"]), a["prefix"], native(gateway) if gateway else 0] for a in entries]),
|
||||
"Routes": v("aau", []),
|
||||
"NameserverData": v("aa{sv}", [{"address": v("s", ip)} for ip in dns]),
|
||||
"Nameservers": v("au", [native(ip) for ip in dns]),
|
||||
"WinsServerData": v("as", []), "WinsServers": v("au", []),
|
||||
})
|
||||
else:
|
||||
packed = lambda ip: list(socket.inet_pton(socket.AF_INET6, ip))
|
||||
props.update({
|
||||
"Addresses": v("a(ayuay)", [(packed(a["address"]), a["prefix"], packed(gateway) if gateway else [0] * 16) for a in entries]),
|
||||
"Routes": v("a(ayuayu)", []), "Nameservers": v("aay", [packed(ip) for ip in dns]),
|
||||
})
|
||||
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))
|
||||
cellular = transport == "cellular"
|
||||
kind = connection_type(state)
|
||||
ip4 = up and bool(family_addresses(state, 4))
|
||||
ip6 = up and bool(family_addresses(state, 6))
|
||||
device_state = 100 if up else 30
|
||||
found = {
|
||||
ROOT: {NAME: {
|
||||
"Devices": v("ao", [DEVICE]),
|
||||
"AllDevices": v("ao", [DEVICE]),
|
||||
"Devices": v("ao", [device]), "AllDevices": v("ao", [device]),
|
||||
"ActiveConnections": v("ao", [ACTIVE] if up else []),
|
||||
"PrimaryConnection": v("o", ACTIVE if up else "/"),
|
||||
"PrimaryConnectionType": v("s", "802-3-ethernet" if up else ""),
|
||||
"ActivatingConnection": v("o", "/"),
|
||||
"PrimaryConnectionType": v("s", kind if up else ""), "ActivatingConnection": v("o", "/"),
|
||||
"NetworkingEnabled": v("b", True),
|
||||
"WirelessEnabled": v("b", False),
|
||||
"WirelessHardwareEnabled": v("b", False),
|
||||
"WwanEnabled": v("b", False),
|
||||
"WwanHardwareEnabled": v("b", False),
|
||||
"Startup": v("b", False),
|
||||
"Version": v("s", "1.46.0"),
|
||||
"State": v("u", NM_STATE_CONNECTED_GLOBAL if up else NM_STATE_DISCONNECTED),
|
||||
"Connectivity": v("u", NM_CONNECTIVITY_FULL if up else NM_CONNECTIVITY_NONE),
|
||||
"ConnectivityCheckAvailable": v("b", False),
|
||||
"ConnectivityCheckEnabled": v("b", False),
|
||||
"Metered": v("u", 0),
|
||||
"WirelessEnabled": v("b", bool(state.get("wifiEnabled", wifi))),
|
||||
"WirelessHardwareEnabled": v("b", bool(state.get("wifiEnabled", wifi))),
|
||||
"WwanEnabled": v("b", cellular), "WwanHardwareEnabled": v("b", cellular),
|
||||
"Startup": v("b", False), "Version": v("s", "1.46.0"),
|
||||
"State": v("u", (70 if state.get("validated") else 60) if up else 20),
|
||||
"Connectivity": v("u", connectivity(state)),
|
||||
"ConnectivityCheckAvailable": v("b", False), "ConnectivityCheckEnabled": v("b", False),
|
||||
"Metered": v("u", metered(state)),
|
||||
}},
|
||||
SETTINGS: {NAME + ".Settings": {
|
||||
"Connections": v("ao", [PROFILE]),
|
||||
"Hostname": v("s", socket.gethostname()),
|
||||
"CanModify": v("b", False),
|
||||
"Connections": v("ao", [PROFILE]), "Hostname": v("s", socket.gethostname()), "CanModify": v("b", False),
|
||||
}},
|
||||
PROFILE: {NAME + ".Settings.Connection": {
|
||||
"Unsaved": v("b", False),
|
||||
"Flags": v("u", 0),
|
||||
"Filename": v("s", ""),
|
||||
"Unsaved": v("b", True), "Flags": v("u", 0), "Filename": v("s", ""),
|
||||
}},
|
||||
device: {NAME + ".Device": {
|
||||
"Interface": v("s", state.get("interface", "android")),
|
||||
"IpInterface": v("s", state.get("interface", "android") if up else ""),
|
||||
"Driver": v("s", "android"),
|
||||
"DeviceType": v("u", 2 if wifi else 8 if cellular else {"ethernet": 1, "vpn": 16}.get(transport, 14)),
|
||||
"State": v("u", device_state), "StateReason": v("(uu)", (device_state, 0)),
|
||||
"ActiveConnection": v("o", ACTIVE if up else "/"),
|
||||
"Ip4Config": v("o", IP4 if ip4 else "/"), "Ip6Config": v("o", IP6 if ip6 else "/"),
|
||||
"Dhcp4Config": v("o", "/"), "Dhcp6Config": v("o", "/"),
|
||||
"AvailableConnections": v("ao", [PROFILE]), "Managed": v("b", True),
|
||||
"Autoconnect": v("b", False), "Real": v("b", True), "Capabilities": v("u", 1),
|
||||
"Mtu": v("u", state.get("mtu", 1500)), "HwAddress": v("s", ""), "Metered": v("u", metered(state)),
|
||||
}},
|
||||
DEVICE: {
|
||||
NAME + ".Device": {
|
||||
"Interface": v("s", "android"),
|
||||
"IpInterface": v("s", "android" if up else ""),
|
||||
"Driver": v("s", "android"),
|
||||
"DeviceType": v("u", NM_DEVICE_TYPE_ETHERNET),
|
||||
"State": v("u", NM_DEVICE_STATE_ACTIVATED if up else NM_DEVICE_STATE_DISCONNECTED),
|
||||
"StateReason": v("(uu)", (NM_DEVICE_STATE_ACTIVATED if up else NM_DEVICE_STATE_DISCONNECTED, 0)),
|
||||
"ActiveConnection": v("o", ACTIVE if up else "/"),
|
||||
"Ip4Config": v("o", IP4 if up else "/"),
|
||||
"Ip6Config": v("o", "/"),
|
||||
"Dhcp4Config": v("o", "/"),
|
||||
"Dhcp6Config": v("o", "/"),
|
||||
"AvailableConnections": v("ao", [PROFILE]),
|
||||
"Managed": v("b", True),
|
||||
"Autoconnect": v("b", True),
|
||||
"Real": v("b", True),
|
||||
"Capabilities": v("u", 1),
|
||||
"Mtu": v("u", 1500),
|
||||
"HwAddress": v("s", ""),
|
||||
},
|
||||
NAME + ".Device.Wired": {
|
||||
"HwAddress": v("s", ""),
|
||||
"PermHwAddress": v("s", ""),
|
||||
"Speed": v("u", 0),
|
||||
"Carrier": v("b", up),
|
||||
},
|
||||
},
|
||||
}
|
||||
if wifi:
|
||||
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", list(aps)), "ActiveAccessPoint": v("o", current_ap),
|
||||
"LastScan": v("x", state.get("lastScan", -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),
|
||||
"DeviceId": v("s", "android"), "OperatorCode": v("s", ""), "Apn": v("s", ""),
|
||||
}
|
||||
elif transport == "ethernet":
|
||||
found[device][NAME + ".Device.Wired"] = {
|
||||
"HwAddress": v("s", ""), "PermHwAddress": v("s", ""), "Speed": v("u", 0), "Carrier": v("b", up),
|
||||
}
|
||||
if up:
|
||||
found[ACTIVE] = {NAME + ".Connection.Active": {
|
||||
"Connection": v("o", PROFILE),
|
||||
"SpecificObject": v("o", "/"),
|
||||
"Id": v("s", "Android"),
|
||||
"Uuid": v("s", UUID),
|
||||
"Type": v("s", "802-3-ethernet"),
|
||||
"Devices": v("ao", [DEVICE]),
|
||||
"State": v("u", NM_ACTIVE_CONNECTION_STATE_ACTIVATED),
|
||||
"StateFlags": v("u", 0),
|
||||
"Default": v("b", True),
|
||||
"Ip4Config": v("o", IP4),
|
||||
"Dhcp4Config": v("o", "/"),
|
||||
"Default6": v("b", False),
|
||||
"Ip6Config": v("o", "/"),
|
||||
"Dhcp6Config": v("o", "/"),
|
||||
"Vpn": v("b", False),
|
||||
"Master": v("o", "/"),
|
||||
}}
|
||||
found[IP4] = {NAME + ".IP4Config": {
|
||||
# The one address the app can see; the prefix says only that much is known.
|
||||
"AddressData": v("aa{sv}", [{"address": v("s", ip), "prefix": v("u", 32)}]),
|
||||
"Addresses": v("aau", []),
|
||||
"Gateway": v("s", ""),
|
||||
"RouteData": v("aa{sv}", []),
|
||||
"Routes": v("aau", []),
|
||||
"NameserverData": v("aa{sv}", []),
|
||||
"Nameservers": v("au", []),
|
||||
"Domains": v("as", []),
|
||||
"Searches": v("as", []),
|
||||
"DnsOptions": v("as", []),
|
||||
"DnsPriority": v("i", 0),
|
||||
"WinsServerData": v("as", []),
|
||||
"WinsServers": v("au", []),
|
||||
"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),
|
||||
"Ip4Config": v("o", IP4 if ip4 else "/"), "Ip6Config": v("o", IP6 if ip6 else "/"),
|
||||
"Dhcp4Config": v("o", "/"), "Dhcp6Config": v("o", "/"), "Vpn": v("b", False), "Master": v("o", "/"),
|
||||
}}
|
||||
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
|
||||
|
||||
|
||||
def settings(state):
|
||||
result = {"connection": {
|
||||
"id": v("s", connection_name(state)), "uuid": v("s", UUID), "type": v("s", connection_type(state)),
|
||||
"interface-name": v("s", state.get("interface", "android")), "metered": v("u", metered(state)),
|
||||
}}
|
||||
if state.get("transport") == "wifi":
|
||||
result["802-11-wireless"] = {
|
||||
"ssid": v("ay", list((state.get("ssid") or "Wi-Fi").encode("utf-8"))), "mode": v("s", "infrastructure"),
|
||||
}
|
||||
elif state.get("transport") == "cellular":
|
||||
result["gsm"] = {} # Android owns the SIM/APN; no credentials are exported.
|
||||
return result
|
||||
|
||||
|
||||
def interface_info(interface, values):
|
||||
# Register properties on the actual objects as well as returning ObjectManager snapshots.
|
||||
# Steam/libnm also use Properties.Get/GetAll and introspect the wireless methods.
|
||||
props = "".join(f'<property name="{escape(key)}" type="{value.get_type_string()}" access="read"/>'
|
||||
for key, value in values.items())
|
||||
node = Gio.DBusNodeInfo.new_for_xml(f'<node><interface name="{interface}">{METHODS.get(interface, "")}{props}</interface></node>')
|
||||
return node.interfaces[0]
|
||||
|
||||
|
||||
class NetworkManager:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
self.ip = address()
|
||||
node = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION)
|
||||
manager, root, profile, device = node.interfaces
|
||||
for path, interface in (("/org/freedesktop", manager), (ROOT, root), (PROFILE, profile), (DEVICE, device)):
|
||||
bus.register_object_with_closures2(path, interface, self.call, None, None)
|
||||
GLib.timeout_add_seconds(CHECK_SECONDS, self.check)
|
||||
self.state = read_snapshot() or legacy_snapshot()
|
||||
self.objects = objects(self.state)
|
||||
self.registrations = {}
|
||||
for path in ("/org/freedesktop", ROOT):
|
||||
bus.register_object(path, interface_info(OBJECT_MANAGER, {}), self.call, None, None)
|
||||
self.register(self.objects)
|
||||
GLib.timeout_add_seconds(1, self.check)
|
||||
|
||||
def register(self, found):
|
||||
wanted = {(path, interface) for path, interfaces in found.items() for interface in interfaces}
|
||||
for key in self.registrations.keys() - wanted:
|
||||
self.bus.unregister_object(self.registrations.pop(key))
|
||||
for path, interface in wanted - self.registrations.keys():
|
||||
self.registrations[(path, interface)] = self.bus.register_object(
|
||||
path, interface_info(interface, found[path][interface]), self.call, self.get_property, None)
|
||||
|
||||
def get_property(self, bus, sender, path, interface, name):
|
||||
return self.objects.get(path, {}).get(interface, {}).get(name)
|
||||
|
||||
def call(self, bus, sender, path, interface, method, args, invocation):
|
||||
if method == "GetManagedObjects":
|
||||
invocation.return_value(v("(a{oa{sa{sv}}})", (objects(self.ip),)))
|
||||
invocation.return_value(v("(a{oa{sa{sv}}})", (self.objects,)))
|
||||
elif method == "GetPermissions":
|
||||
invocation.return_value(v("(a{ss})", ({},)))
|
||||
elif method == "CheckConnectivity":
|
||||
self.check()
|
||||
invocation.return_value(v("(u)", (NM_CONNECTIVITY_FULL if self.ip else NM_CONNECTIVITY_NONE,)))
|
||||
invocation.return_value(v("(u)", (connectivity(self.state),)))
|
||||
elif method == "GetSettings":
|
||||
# The name the client shows the connection under.
|
||||
invocation.return_value(v("(a{sa{sv}})", ({"connection": {
|
||||
"id": v("s", "Android"), "uuid": v("s", UUID), "type": v("s", "802-3-ethernet")}},)))
|
||||
invocation.return_value(v("(a{sa{sv}})", (settings(self.state),)))
|
||||
elif method == "ListConnections":
|
||||
invocation.return_value(v("(ao)", ([PROFILE],)))
|
||||
elif method in ("GetAccessPoints", "GetAllAccessPoints"):
|
||||
invocation.return_value(v("(ao)", (self.objects[path][NAME + ".Device.Wireless"]["AccessPoints"].unpack(),)))
|
||||
elif method == "RequestScan":
|
||||
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)", (self.objects[ROOT][NAME]["Devices"].unpack(),)))
|
||||
else:
|
||||
invocation.return_value(v("(ao)", ([DEVICE],)))
|
||||
invocation.return_dbus_error(NAME + ".NotSupported", "Manage this connection in Android settings")
|
||||
|
||||
def check(self):
|
||||
"""Tells the bus when Android gains or loses its route, as NetworkManager would."""
|
||||
ip = address()
|
||||
if (ip is None) != (self.ip is None) or (ip and ip != self.ip):
|
||||
before, after = objects(self.ip), objects(ip)
|
||||
self.ip = ip
|
||||
for path in before.keys() - after.keys():
|
||||
self.announce("InterfacesRemoved", path, v("(oas)", (path, list(before[path]))))
|
||||
for path in after.keys() - before.keys():
|
||||
self.announce("InterfacesAdded", path, v("(oa{sa{sv}})", (path, after[path])))
|
||||
for path in after.keys() & before.keys():
|
||||
for interface, values in after[path].items():
|
||||
self.bus.emit_signal(None, path, "org.freedesktop.DBus.Properties", "PropertiesChanged",
|
||||
v("(sa{sv}as)", (interface, values, [])))
|
||||
state = after[ROOT][NAME]["State"].unpack()
|
||||
device = after[DEVICE][NAME + ".Device"]["State"].unpack()
|
||||
was = before[DEVICE][NAME + ".Device"]["State"].unpack()
|
||||
self.bus.emit_signal(None, ROOT, NAME, "StateChanged", v("(u)", (state,)))
|
||||
self.bus.emit_signal(None, DEVICE, NAME + ".Device", "StateChanged", v("(uuu)", (device, was, 0)))
|
||||
state = read_snapshot()
|
||||
if state is None:
|
||||
return True # A transient read failure must not replace a known link with Ethernet.
|
||||
if state == self.state:
|
||||
return True
|
||||
before, after = self.objects, objects(state)
|
||||
old_state = self.state
|
||||
self.state, self.objects = state, after
|
||||
self.register(after)
|
||||
for path in before.keys() | after.keys():
|
||||
removed = before.get(path, {}).keys() - after.get(path, {}).keys()
|
||||
added = after.get(path, {}).keys() - before.get(path, {}).keys()
|
||||
if removed:
|
||||
self.announce("InterfacesRemoved", v("(oas)", (path, list(removed))))
|
||||
if added:
|
||||
self.announce("InterfacesAdded", v("(oa{sa{sv}})", (path, {i: after[path][i] for i in added})))
|
||||
for interface in before.get(path, {}).keys() & after.get(path, {}).keys():
|
||||
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, [])))
|
||||
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:
|
||||
self.bus.emit_signal(None, ROOT, NAME, "StateChanged", v("(u)", (now.unpack(),)))
|
||||
device = device_path(state)
|
||||
if device in before:
|
||||
was = before[device][NAME + ".Device"]["State"]
|
||||
now = after[device][NAME + ".Device"]["State"]
|
||||
if now != was:
|
||||
self.bus.emit_signal(None, device, NAME + ".Device", "StateChanged", v("(uuu)", (now.unpack(), was.unpack(), 0)))
|
||||
if settings(old_state) != settings(state):
|
||||
self.bus.emit_signal(None, PROFILE, NAME + ".Settings.Connection", "Updated", v("()", ()))
|
||||
return True
|
||||
|
||||
def announce(self, signal, path, body):
|
||||
self.bus.emit_signal(None, "/org/freedesktop", "org.freedesktop.DBus.ObjectManager", signal, body)
|
||||
def announce(self, signal, body):
|
||||
for path in ("/org/freedesktop", ROOT):
|
||||
self.bus.emit_signal(None, path, OBJECT_MANAGER, signal, body)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -216,6 +216,12 @@ reap_orphans() {
|
||||
done
|
||||
}
|
||||
|
||||
# Gamescope's Wayland backend does not forward the outer clipboard into Xwayland.
|
||||
# This helper owns only Android text selections and exits with this guest session.
|
||||
if [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
|
||||
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
|
||||
fi
|
||||
|
||||
case $mode in
|
||||
desktop)
|
||||
exec pcmanfm
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"""NetworkManager contract and real D-Bus handovers (requires python3-gi and dbus).
|
||||
|
||||
Run on Linux: dbus-run-session -- python3 -m unittest discover -s tools/tests -p test_netmanager.py
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib
|
||||
except ImportError:
|
||||
Gio = GLib = None
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/bannerlator-netmanager"
|
||||
if Gio:
|
||||
loader = importlib.machinery.SourceFileLoader("netmanager", str(SCRIPT))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
nm = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(nm)
|
||||
|
||||
WIFI = {
|
||||
"connected": True, "transport": "wifi", "interface": "wlan0", "wifiEnabled": True,
|
||||
"validated": True, "captivePortal": False, "metered": False,
|
||||
"ssid": "Test \"Wi-Fi\" ☃", "strength": 73, "frequency": 5180, "bitrate": 866000,
|
||||
"addresses": [{"address": "192.0.2.2", "prefix": 24}, {"address": "2001:db8::2", "prefix": 64}],
|
||||
"gateways": ["192.0.2.1", "2001:db8::1"], "dns": ["192.0.2.1", "2001:db8::1"],
|
||||
}
|
||||
CELLULAR = {
|
||||
"connected": True, "transport": "cellular", "interface": "rmnet_data0", "wifiEnabled": True,
|
||||
"validated": True, "metered": True,
|
||||
"addresses": [{"address": "2001:db8:1::2", "prefix": 64}],
|
||||
"gateways": ["2001:db8:1::1"], "dns": ["2001:db8:1::1"],
|
||||
}
|
||||
OFFLINE = {"connected": False, "transport": "none", "wifiEnabled": True, "metered": None}
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio, "requires PyGObject")
|
||||
class NetworkObjectsTest(unittest.TestCase):
|
||||
def test_wifi_graph(self):
|
||||
found = nm.objects(WIFI)
|
||||
manager = found[nm.ROOT][nm.NAME]
|
||||
device = found[nm.device_path(WIFI)]
|
||||
self.assertEqual(manager["PrimaryConnectionType"].unpack(), "802-11-wireless")
|
||||
self.assertTrue(manager["WirelessEnabled"].unpack())
|
||||
self.assertEqual(device[nm.NAME + ".Device"]["DeviceType"].unpack(), 2)
|
||||
self.assertEqual(device[nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), nm.AP)
|
||||
ap = found[nm.AP][nm.NAME + ".AccessPoint"]
|
||||
self.assertEqual(bytes(ap["Ssid"].unpack()).decode(), WIFI["ssid"])
|
||||
self.assertEqual(ap["Strength"].unpack(), 73)
|
||||
self.assertEqual(manager["Metered"].unpack(), 2)
|
||||
for interfaces in found.values():
|
||||
for values in interfaces.values():
|
||||
for value in values.values():
|
||||
if value.get_type_string() == "o" and value.unpack() != "/":
|
||||
self.assertIn(value.unpack(), found)
|
||||
|
||||
def test_cellular_ipv6_only(self):
|
||||
found = nm.objects(CELLULAR)
|
||||
manager = found[nm.ROOT][nm.NAME]
|
||||
device = found[nm.device_path(CELLULAR)]
|
||||
active = found[nm.ACTIVE][nm.NAME + ".Connection.Active"]
|
||||
self.assertEqual(manager["PrimaryConnectionType"].unpack(), "gsm")
|
||||
self.assertEqual(manager["Metered"].unpack(), 1)
|
||||
self.assertEqual(device[nm.NAME + ".Device"]["DeviceType"].unpack(), 8)
|
||||
self.assertIn(nm.NAME + ".Device.Modem", device)
|
||||
self.assertNotIn(nm.AP, found)
|
||||
self.assertNotIn(nm.IP4, found)
|
||||
self.assertEqual(active["Ip4Config"].unpack(), "/")
|
||||
self.assertEqual(active["Ip6Config"].unpack(), nm.IP6)
|
||||
self.assertTrue(active["Default6"].unpack())
|
||||
self.assertFalse(active["Default"].unpack())
|
||||
self.assertNotEqual(nm.device_path(WIFI), nm.device_path(CELLULAR))
|
||||
|
||||
def test_offline_and_captive_portal(self):
|
||||
offline = nm.objects(OFFLINE)
|
||||
self.assertEqual(offline[nm.ROOT][nm.NAME]["State"].unpack(), 20)
|
||||
self.assertEqual(offline[nm.ROOT][nm.NAME]["ActiveConnections"].unpack(), [])
|
||||
self.assertNotIn(nm.AP, offline)
|
||||
self.assertEqual(nm.connectivity(dict(WIFI, validated=False, captivePortal=True)), 2)
|
||||
self.assertEqual(nm.connectivity(dict(WIFI, validated=False, captivePortal=False)), 3)
|
||||
self.assertEqual(nm.metered(OFFLINE), 0)
|
||||
|
||||
def test_redacted_name_and_wired_vpn(self):
|
||||
redacted = dict(WIFI)
|
||||
del redacted["ssid"]
|
||||
self.assertEqual(nm.connection_name(redacted), "Wi-Fi")
|
||||
self.assertEqual(bytes(nm.settings(redacted)["802-11-wireless"]["ssid"].unpack()), b"Wi-Fi")
|
||||
for transport, kind, device_type in (("ethernet", "802-3-ethernet", 1), ("vpn", "tun", 16)):
|
||||
state = dict(WIFI, transport=transport)
|
||||
found = nm.objects(state)
|
||||
self.assertEqual(found[nm.ROOT][nm.NAME]["PrimaryConnectionType"].unpack(), kind)
|
||||
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):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.snapshot = Path(self.temp.name) / "network.json"
|
||||
self.write(WIFI)
|
||||
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]); 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")
|
||||
|
||||
def tearDown(self):
|
||||
self.process.terminate()
|
||||
_, stderr = self.process.communicate(timeout=5)
|
||||
self.temp.cleanup()
|
||||
self.assertEqual(stderr, b"", stderr.decode())
|
||||
|
||||
def write(self, state):
|
||||
staged = self.snapshot.with_suffix(".staged")
|
||||
staged.write_text(json.dumps(state))
|
||||
staged.replace(self.snapshot)
|
||||
|
||||
def call(self, path, interface, method, parameters=None):
|
||||
return self.bus.call_sync(nm.NAME, path, interface, method, parameters, None,
|
||||
Gio.DBusCallFlags.NONE, 1000, None).unpack()
|
||||
|
||||
def prop(self, path, interface, name):
|
||||
return self.call(path, nm.PROPERTIES, "Get", GLib.Variant("(ss)", (interface, name)))[0]
|
||||
|
||||
def await_type(self, expected):
|
||||
deadline = time.monotonic() + 6
|
||||
while time.monotonic() < deadline:
|
||||
if self.process.poll() is not None:
|
||||
self.fail(self.process.communicate()[1].decode())
|
||||
try:
|
||||
if self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType") == expected:
|
||||
return
|
||||
except GLib.Error:
|
||||
pass
|
||||
time.sleep(0.05)
|
||||
self.fail("network type did not change to " + expected)
|
||||
|
||||
def test_direct_properties_methods_and_handover(self):
|
||||
signals = []
|
||||
subscription = self.bus.signal_subscribe(
|
||||
nm.NAME, None, None, None, None, Gio.DBusSignalFlags.NONE,
|
||||
lambda bus, sender, path, interface, member, args: signals.append((path, interface, member, args.unpack())))
|
||||
self.addCleanup(self.bus.signal_unsubscribe, subscription)
|
||||
wifi_path = nm.device_path(WIFI)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device", "DeviceType"), 2)
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 73)
|
||||
self.assertEqual(self.call(wifi_path, nm.NAME + ".Device.Wireless", "GetAccessPoints"), ([nm.AP],))
|
||||
self.assertEqual(self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},))), ())
|
||||
all_props = self.call(nm.ROOT, nm.PROPERTIES, "GetAll", GLib.Variant("(s)", (nm.NAME,)))[0]
|
||||
self.assertTrue(all_props["WirelessEnabled"])
|
||||
introspection = self.call(wifi_path, "org.freedesktop.DBus.Introspectable", "Introspect")[0]
|
||||
self.assertIn("GetAllAccessPoints", introspection)
|
||||
self.write(dict(WIFI, strength=21, ssid="Other Wi-Fi"))
|
||||
deadline = time.monotonic() + 4
|
||||
while self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength") != 21 and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 21)
|
||||
self.assertEqual(self.call(nm.PROFILE, nm.NAME + ".Settings.Connection", "GetSettings")[0]["connection"]["id"], "Other Wi-Fi")
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
cell_path = nm.device_path(CELLULAR)
|
||||
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.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)
|
||||
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,))
|
||||
self.write(WIFI)
|
||||
self.await_type("802-11-wireless")
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 73)
|
||||
context = GLib.MainContext.default()
|
||||
while context.pending():
|
||||
context.iteration(False)
|
||||
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] == 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.
|
||||
self.snapshot.write_text("{")
|
||||
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")
|
||||
from gi.repository import NM
|
||||
except ValueError:
|
||||
self.skipTest("requires gir1.2-nm-1.0")
|
||||
# libnm is a real consumer of the same API Steam reads. It caches objects by path,
|
||||
# so the handover must replace the Wi-Fi device with a modem rather than mutate its type.
|
||||
previous = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS")
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = os.environ["DBUS_SESSION_BUS_ADDRESS"]
|
||||
try:
|
||||
client = NM.Client.new(None)
|
||||
self.assertTrue(client.get_nm_running())
|
||||
wifi = client.get_devices()[0]
|
||||
self.assertIsInstance(wifi, NM.DeviceWifi)
|
||||
self.assertEqual(wifi.get_active_access_point().get_strength(), 73)
|
||||
self.assertEqual(client.get_primary_connection().get_connection_type(), "802-11-wireless")
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
context = GLib.MainContext.default()
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
while context.pending():
|
||||
context.iteration(False)
|
||||
if client.get_devices() and isinstance(client.get_devices()[0], NM.DeviceModem):
|
||||
break
|
||||
time.sleep(0.05)
|
||||
self.assertIsInstance(client.get_devices()[0], NM.DeviceModem)
|
||||
self.assertEqual(client.get_primary_connection().get_connection_type(), "gsm")
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop("DBUS_SYSTEM_BUS_ADDRESS", None)
|
||||
else:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = previous
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user