Compare commits

...

4 Commits

Author SHA1 Message Date
Danny 007935f816 Build 2026-11-23 14:36:46 -08:00
Danny 9d44060e03 MDNS: Add to Comma Menu and Galaxy 2026-11-23 14:34:00 -08:00
Danny 33eaa9d781 Galaxy: Open by galaxy.local on Every Network, Including the Hotspot 2026-11-23 14:34:00 -08:00
Danny 6a33facb4c Galaxy: Hold Connection Slots Only While a Request Runs 2026-11-23 14:34:00 -08:00
13 changed files with 1037 additions and 17 deletions
+44 -2
View File
@@ -1,6 +1,6 @@
"""Bounded Galaxy HTTP connections and shared-source shutdown."""
from contextlib import ExitStack
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from functools import lru_cache
@@ -46,7 +46,8 @@ class ReverseProxy:
class _LocalHTTPServer(ThreadingHTTPServer):
"""Bound idle browser connections without blocking other local requests."""
MAX_CONNECTIONS = 8
MAX_CONNECTIONS = 32 # open sockets, one thread each
MAX_ACTIVE_REQUESTS = 8 # requests being handled; idle keep-alive sockets don't count
# comma's own services call back over loopback while a browser request waits on them.
LOOPBACK_CONNECTIONS = 4
REQUEST_TIMEOUT = 4.0
@@ -54,6 +55,7 @@ class _LocalHTTPServer(ThreadingHTTPServer):
def __init__(self, *args, **kwargs):
self._slots = threading.BoundedSemaphore(self.MAX_CONNECTIONS)
self._loopback_slots = threading.BoundedSemaphore(self.LOOPBACK_CONNECTIONS)
self._active = threading.BoundedSemaphore(self.MAX_ACTIVE_REQUESTS)
self._draining = False
super().__init__(*args, **kwargs)
@@ -94,6 +96,22 @@ class _LocalHTTPServer(ThreadingHTTPServer):
finally:
slots.release()
@contextmanager
def request_slot(self, request):
"""Held while one request is handled; loopback skips it because it serves browser requests in flight."""
if self._draining:
yield False
return
if self.loopback(request):
yield True
return
admitted = self._active.acquire(timeout=self.REQUEST_TIMEOUT)
try:
yield admitted
finally:
if admitted:
self._active.release()
def drain_requests(self, timeout: float) -> bool:
"""Wait for accepted requests before closing their shared data sources."""
self._draining = True
@@ -189,6 +207,12 @@ def allowed_authority(host: str, local_address: str, port: int, *, local_hostnam
if local_hostnames is None:
return False
canonical = dns_authority_name(host, port, allow_portless=allow_portless)
from openpilot.starpilot.galaxy.mdns import own_address, published_record
published = published_record()
# Our mDNS name, with or without :port, on any of our own LAN addresses (port 80 redirects here).
if published is not None and dns_authority_name(host, port, allow_portless=True) == published[0] and \
own_address(local_address):
return True
return canonical is not None and canonical in local_hostnames.names(local_address)
try:
address = ip_address(local_address)
@@ -226,6 +250,24 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args): # noqa: A002 - Match BaseHTTPRequestHandler's keyword signature.
pass
def handle_one_request(self):
slot = getattr(self.server, 'request_slot', None)
if slot is None:
return super().handle_one_request()
try:
# Wait for the next keep-alive request without holding a request slot.
if not self.rfile.peek(1):
self.close_connection = True
return
except TimeoutError:
self.close_connection = True
return
with slot(self.connection) as admitted:
if not admitted:
self.close_connection = True
return
super().handle_one_request()
def handle(self):
try:
super().handle()
+2 -1
View File
@@ -69,7 +69,8 @@ class LocalAccess:
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, AttributeError):
reason = 'The comma could not read its network addresses. Check its Network settings and refresh.'
addresses = []
from openpilot.starpilot.galaxy.mdns import published_url
self.cached = {'available': bool(addresses), 'addresses': addresses,
'reason': '' if addresses else reason}
'reason': '' if addresses else reason, 'name': published_url(self.port) or ''}
self.expiry = self.clock() + 5.0
return self.cached
+9 -1
View File
@@ -5,6 +5,7 @@ import signal
import threading
import time
from openpilot.starpilot.galaxy.mdns import run as run_mdns
from openpilot.starpilot.galaxy.server import make_server
from openpilot.starpilot.galaxy.server import make_remote_server
from openpilot.starpilot.galaxy.remote import default_remote_pairing, make_gateway_auth_server
@@ -126,7 +127,14 @@ def main() -> None:
server.server_close()
raise
print(f'Galaxy local/LAN service listening on port {server.server_port}', flush=True)
serve_managed(server, extra_servers=(remote_server, auth_server), tunnel=lambda stop: supervise_tunnel(stop, pairing))
mdns_stop = threading.Event()
mdns = threading.Thread(target=run_mdns, args=(mdns_stop, server.server_port), name='galaxy-mdns', daemon=True)
mdns.start()
try:
serve_managed(server, extra_servers=(remote_server, auth_server), tunnel=lambda stop: supervise_tunnel(stop, pairing))
finally:
mdns_stop.set()
mdns.join(timeout=3)
if __name__ == '__main__':
+371
View File
@@ -0,0 +1,371 @@
"""Advertise galaxy.local through avahi's D-Bus API, answering with each interface's own address."""
import fcntl
from ipaddress import IPv6Address
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
import time
from jeepney import DBusAddress, new_method_call
from jeepney.io.blocking import open_dbus_connection
from jeepney.low_level import HeaderFields, MessageType
from openpilot.starpilot.galaxy.hotspot import INTERFACE as HOTSPOT_INTERFACE
from openpilot.starpilot.galaxy.local_hostnames import lan_address
NAMES = ('galaxy.local',) + tuple(f'galaxy-{n}.local' for n in range(2, 10))
INTERFACES = ('wlan0', 'eth0', HOTSPOT_INTERFACE)
NAME_FILE = Path('/data/galaxy/mdns_name')
IF_INET6 = Path('/proc/net/if_inet6')
SIOCGIFADDR = 0x8915
CHAIN = 'GALAXY_HTTP'
MAX_READ_BYTES = 65536
REFRESH_S = 10.0
ESTABLISH_S = 5.0
RETRY_S = 300.0
CALL_S = 5.0
RESOLVE_S = 1.5
AVAHI = 'org.freedesktop.Avahi'
SERVER = 'org.freedesktop.Avahi.Server'
ENTRY_GROUP = 'org.freedesktop.Avahi.EntryGroup'
PROTO_INET, PROTO_INET6 = 0, 1
PUBLISH_NO_REVERSE = 16
ESTABLISHED = 2
_published = None
_redirected = False
def published_record():
return _published
def published_url(port):
"""Our published name as a link; port-less only while port 80 redirects to Galaxy."""
published = _published
if published is None:
return None
return f'http://{published[0]}/' if _redirected else f'http://{published[0]}:{port}/'
def _ifaddr(sock, name):
return socket.inet_ntoa(fcntl.ioctl(sock.fileno(), SIOCGIFADDR, struct.pack('256s', name.encode()))[20:24])
def interface_addresses(lookup=_ifaddr):
"""Primary IPv4 of each candidate interface, read by ioctl."""
addresses = {}
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
for name in INTERFACES:
try:
addresses[name] = lookup(sock, name)
except OSError:
continue # interface missing or has no IPv4 address
except OSError:
return {}
return addresses
def _read_text(path, limit=MAX_READ_BYTES):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as handle:
data = handle.read(limit + 1)
if len(data) > limit:
raise ValueError(f'{path} exceeds {limit} bytes')
return data.decode()
def own_address(address):
"""True for this device's current wlan0/eth0/galaxy0 LAN address."""
return lan_address(address) and address in interface_addresses().values()
class Redirect:
"""Redirect port 80 on this device's own LAN addresses to Galaxy; one -d rule each, never forwarded traffic."""
def __init__(self, port, run=subprocess.run, which=shutil.which):
self.port, self.run = port, run
self.firewall = which('iptables-legacy') or which('iptables')
self.ready, self.applied = False, None
def ipt(self, *args, check=True):
if self.firewall is None:
raise OSError('iptables missing')
return self.run(['sudo', '-n', self.firewall, '-w', '2', '-t', 'nat', *args], capture_output=True, timeout=5, check=check)
def sync(self, addresses):
global _redirected
wanted = tuple(sorted(a for a in addresses if lan_address(a)))
if self.firewall is None or wanted == self.applied:
return
try:
if not self.ready:
self.ipt('-N', CHAIN, check=False) # already exists after a restart
jump = ('PREROUTING', '-p', 'tcp', '--dport', '80', '-j', CHAIN)
if self.ipt('-C', *jump, check=False).returncode != 0:
self.ipt('-I', *jump)
self.ready = True
self.ipt('-F', CHAIN)
for address in wanted:
self.ipt('-A', CHAIN, '-d', address, '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', str(self.port))
self.applied, _redirected = wanted, True
except (OSError, subprocess.SubprocessError) as error:
self.applied, _redirected = wanted, False # retried on the next address change, not every poll
_log(f'port 80 redirect failed ({error}); http://galaxy.local needs :{self.port}')
def close(self):
global _redirected
_redirected = False
if not self.ready:
return
try:
self.ipt('-D', 'PREROUTING', '-p', 'tcp', '--dport', '80', '-j', CHAIN, check=False)
self.ipt('-F', CHAIN, check=False)
self.ipt('-X', CHAIN, check=False)
except (OSError, subprocess.SubprocessError) as error:
_log(f'port 80 redirect cleanup failed ({error})')
self.ready, self.applied = False, None
def link_local(interface, path=IF_INET6):
"""The interface's fe80:: address, so AAAA lookups answer at once."""
try:
for line in _read_text(path).splitlines():
fields = line.split()
# address ifindex prefixlen scope flags name; scope 0x20 = link
if len(fields) == 6 and fields[5] == interface and fields[3] == '20':
return str(IPv6Address(bytes.fromhex(fields[0])))
except (OSError, ValueError):
pass
return None
def records(found, ipv6=link_local, index=socket.if_nametoindex):
"""(interface index, protocol, address) for each LAN interface."""
out = []
for name in INTERFACES:
address = found.get(name)
if address is None or not lan_address(address):
continue
try:
number = index(name)
except OSError:
continue
out.append((number, PROTO_INET, address))
address6 = ipv6(name)
if address6 is not None:
out.append((number, PROTO_INET6, address6))
return tuple(out)
class AvahiError(Exception):
def __init__(self, name, message=''):
super().__init__(f'{name}: {message}' if message else name)
self.name = name
@property
def collision(self):
return self.name == 'org.freedesktop.Avahi.CollisionError'
class Avahi:
"""Entry groups belong to this D-Bus connection, so avahi withdraws them if Galaxy dies."""
def __init__(self, connect=lambda: open_dbus_connection(bus='SYSTEM'), stopped=lambda: False):
self.connect, self.stopped, self.connection = connect, stopped, None
def call(self, path, interface, member, signature=None, body=()):
if self.connection is None:
self.connection = self.connect()
address = DBusAddress(path, bus_name=AVAHI, interface=interface)
message = new_method_call(address, member, signature, body) if signature else new_method_call(address, member)
try:
reply = self.connection.send_and_get_reply(message, timeout=CALL_S)
except OSError:
self.close()
raise
if reply.header.message_type == MessageType.error:
raise AvahiError(str(reply.header.fields.get(HeaderFields.error_name, member)), str(reply.body[0]) if reply.body else '')
return reply.body
def first(self, path, interface, member, kind):
body = self.call(path, interface, member)
if len(body) != 1 or not isinstance(body[0], kind):
raise AvahiError(f'{member} returned {body!r}')
return body[0]
def state(self, group):
return self.first(group, ENTRY_GROUP, 'GetState', int)
def claim(self, name, entries, timeout=ESTABLISH_S, group=None):
"""The committed group once avahi has probed the name, or None if another device holds it; group updates ours in place."""
if group is None:
group = self.first('/', SERVER, 'EntryGroupNew', str)
else:
self.call(group, ENTRY_GROUP, 'Reset')
try:
for number, protocol, address in entries:
self.call(group, ENTRY_GROUP, 'AddAddress', 'iiuss', (number, protocol, PUBLISH_NO_REVERSE, name, address))
self.call(group, ENTRY_GROUP, 'Commit')
deadline = time.monotonic() + timeout
while (state := self.state(group)) < ESTABLISHED and time.monotonic() < deadline and not self.stopped():
time.sleep(0.1)
if state == ESTABLISHED:
return group
except AvahiError as error:
if not error.collision:
self.free(group)
raise
self.free(group)
return None
def free(self, group):
try:
self.call(group, ENTRY_GROUP, 'Free')
except (OSError, AvahiError):
pass # already withdrawn, or the connection is gone and avahi dropped it
def close(self):
if self.connection is not None:
try:
self.connection.close()
except OSError:
pass
self.connection = None
def load_name(path=NAME_FILE):
try:
name = _read_text(path, 64).strip()
except (OSError, ValueError):
return None
return name if name in NAMES else None
def save_name(name, path=NAME_FILE):
try:
tmp = path.with_suffix('.tmp')
tmp.write_text(name + '\n')
os.replace(tmp, path)
except OSError as error:
_log(f'cannot remember {name} ({error})')
def candidates(remembered):
return ((remembered,) if remembered else ()) + tuple(name for name in NAMES if name != remembered)
def held_elsewhere(name, own, run=subprocess.run):
"""True when another device already answers for name; probing alone can miss a responder that doesn't defend."""
try:
out = run(['avahi-resolve', '-4', '-n', name], capture_output=True, text=True, timeout=RESOLVE_S).stdout
except (OSError, subprocess.SubprocessError):
return False
fields = out.split()
return len(fields) == 2 and fields[0] == name and fields[1] not in own
def _claim(avahi, entries, remembered, stop, taken=held_elsewhere, ours=frozenset()):
own = {address for _, _, address in entries} | set(ours) # our earlier addresses can linger in avahi's answers
for name in candidates(remembered):
if stop.is_set():
break
if taken(name, own):
continue
group = avahi.claim(name, entries)
if group is not None:
return name, group
return None, None
def _log(message, warning=True):
from openpilot.common.swaglog import cloudlog
(cloudlog.warning if warning else cloudlog.info)(f'Galaxy mDNS: {message}')
def publish(stop, *, avahi=None, addresses=interface_addresses, ipv6=link_local, index=socket.if_nametoindex, redirect=None,
taken=held_elsewhere, name_file=NAME_FILE, refresh=REFRESH_S, retry=RETRY_S):
"""Keep the first free galaxy[-N].local name on every LAN interface until stop is set."""
global _published
avahi = avahi if avahi is not None else Avahi(stopped=stop.is_set)
group, entries, retry_at, failure = None, (), 0.0, None
remembered, ours = load_name(name_file), set()
def failed(message):
nonlocal failure
if message != failure:
failure = message
_log(f'{message}; retrying every {retry:.0f}s')
try:
while not stop.is_set():
found = addresses()
if redirect is not None:
redirect.sync(found.values())
wanted = records(found, ipv6, index)
lost = False
if group is not None:
try:
lost = avahi.state(group) != ESTABLISHED
except (OSError, AvahiError):
lost = True
if lost and _published is not None:
_log(f'lost {_published[0]}; reclaiming')
if wanted != entries or lost or (group is None and wanted and time.monotonic() >= retry_at):
held = _published[0] if _published is not None and group is not None and not lost and wanted else None
if held is not None:
try:
group = avahi.claim(held, wanted, group=group)
except (OSError, AvahiError):
group = None
if group is not None and held is None:
avahi.free(group)
group = None
_published, entries = None, wanted
if wanted:
name = held if group is not None else None
try:
if name is None:
name, group = _claim(avahi, wanted, remembered, stop, taken, ours)
except (OSError, AvahiError) as error:
failed(f'avahi unavailable ({error})')
else:
if name is None:
failed('every galaxy[-N].local name is taken')
if name is None:
retry_at = time.monotonic() + retry
else:
failure = None
ours.update(address for _, _, address in wanted)
_published = (name, tuple(address for _, protocol, address in wanted if protocol == PROTO_INET))
interfaces = ', '.join(n for n in INTERFACES if found.get(n) in _published[1])
_log(f'published {name} on {interfaces}', warning=False)
if name != remembered:
remembered = name
save_name(name, name_file)
stop.wait(refresh)
finally:
if group is not None:
avahi.free(group)
avahi.close()
_published = None
def run(stop, port):
redirect = Redirect(port)
try:
publish(stop, redirect=redirect)
except Exception:
from openpilot.common.swaglog import cloudlog
cloudlog.exception('Galaxy mDNS: publisher stopped; galaxy.local is offline, the IP address still works')
finally:
redirect.close()
@@ -11,8 +11,10 @@ from typing import Any
from urllib.parse import urlsplit
import pytest
from unittest.mock import patch
from openpilot.starpilot.galaxy.http_server import _LocalHTTPHandler, _LocalHTTPServer
from openpilot.starpilot.galaxy import mdns
from openpilot.starpilot.galaxy.http_server import _LocalHTTPHandler, _LocalHTTPServer, allowed_authority
from openpilot.starpilot.galaxy.replay_http import ReplayHTTP
from openpilot.starpilot.galaxy.recording_http import send_recording
@@ -164,6 +166,52 @@ def test_idle_persistent_connections_release_capacity(server):
connection.close()
def test_busy_keepalive_tabs_do_not_hold_request_slots(server, monkeypatch):
"""Two polling tabs' worth of keep-alive sockets must not starve a third tab's first load."""
running, _, _ = server
monkeypatch.setattr(running, 'loopback', lambda request: False)
held = []
try:
for _ in range(running.MAX_ACTIVE_REQUESTS + 4):
connection = http.client.HTTPConnection('127.0.0.1', running.server_port, timeout=2)
held.append(connection)
connection.request('GET', '/poll')
assert connection.getresponse().read() == b'ok'
started = time.monotonic()
with closing(http.client.HTTPConnection('127.0.0.1', running.server_port, timeout=2)) as opening:
opening.request('GET', '/css/galaxy.css')
assert opening.getresponse().read() == b'ok'
assert time.monotonic() - started < 1
# The held sockets are still usable keep-alive connections.
for connection in held:
connection.request('GET', '/poll')
assert connection.getresponse().read() == b'ok'
finally:
for connection in held:
connection.close()
def test_requests_in_flight_are_bounded(server, monkeypatch):
running, _, _ = server
monkeypatch.setattr(running, 'loopback', lambda request: False)
for _ in range(running.MAX_ACTIVE_REQUESTS):
assert running._active.acquire(blocking=False)
monkeypatch.setattr(running, 'REQUEST_TIMEOUT', .2)
try:
with closing(socket.create_connection(('127.0.0.1', running.server_port), timeout=2)) as waiting:
waiting.sendall(b'GET /blocked HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n')
try:
assert waiting.recv(64) == b''
except ConnectionResetError:
pass
finally:
for _ in range(running.MAX_ACTIVE_REQUESTS):
running._active.release()
with closing(http.client.HTTPConnection('127.0.0.1', running.server_port, timeout=2)) as later:
later.request('GET', '/after')
assert later.getresponse().read() == b'ok'
def test_full_browser_pool_still_serves_comma_services(server):
running, _, _ = server
held = []
@@ -223,3 +271,23 @@ def test_drain_turns_away_requests_still_waiting_for_capacity(server, monkeypatc
finally:
for connection in held:
connection.close()
def test_authority_admits_only_published_mdns_name_on_own_lan_address():
names = SimpleNamespace(names=lambda destination: ())
own = {'wlan0': '192.168.35.249', 'galaxy0': '172.31.254.1'}
with patch.object(mdns, '_published', ('galaxy-2.local', '192.168.35.249')), \
patch.object(mdns, 'interface_addresses', return_value=own):
assert allowed_authority('galaxy-2.local:8082', '192.168.35.249', 8082, local_hostnames=names)
assert allowed_authority('GALAXY-2.local.:8082', '192.168.35.249', 8082, local_hostnames=names)
# Port 80 is redirected to Galaxy, so the browser sends no port.
assert allowed_authority('galaxy-2.local', '192.168.35.249', 8082, local_hostnames=names)
# Hotspot clients: REDIRECT rewrites the destination to galaxy0's address.
assert allowed_authority('galaxy-2.local', '172.31.254.1', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local:9999', '192.168.35.249', 8082, local_hostnames=names)
assert not allowed_authority('galaxy.local', '192.168.35.249', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '10.228.238.20', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '127.0.0.1', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '100.64.1.5', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '192.168.35.249', 8082, local_hostnames=None)
assert not allowed_authority('galaxy-2.local', '192.168.35.249', 8082, local_hostnames=names)
@@ -9,6 +9,12 @@ assert.equal(validLocalAccess({ available: false, addresses: [], reason: 'No act
assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'javascript:alert(1)' }] }), false)
assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'http://password@example.com' }] }), false)
assert.equal(validLocalAccess({ ...snapshot, available: false }), false)
assert.equal(validLocalAccess({ ...snapshot, name: 'http://galaxy-2.local/' }), true)
assert.equal(validLocalAccess({ ...snapshot, name: 'http://galaxy.local:8082/' }), true)
assert.equal(validLocalAccess({ ...snapshot, name: '' }), true)
assert.equal(validLocalAccess({ ...snapshot, name: 'javascript:alert(1)' }), false)
assert.equal(validLocalAccess({ ...snapshot, name: 'http://evil.example/' }), false)
assert.equal(validLocalAccess({ ...snapshot, name: { toString: () => 'http://galaxy.local/' } }), false)
const updates = [], requests = [], timers = []
let auth = 0
const feed = new LocalAccessFeed({ publish: value => updates.push(value), onUnauthorized: () => auth++,
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { translateText, localizeDocument } from "../web/js/localization.js"
import { translateText, localizeDocument, startLocalization, LANGUAGE_RECHECK_MS, LANGUAGE_RETRY_MS } from "../web/js/localization.js"
assert.equal(translateText(" Home\n", { Home: "ホーム" }), " ホーム\n")
assert.equal(translateText("SpeedLimitController", {}), "SpeedLimitController")
@@ -67,3 +67,38 @@ const hiddenNative = new Element("select", {hidden:""}, [new Element("option", {
localizeDocument(hiddenNative, {language:"ja",messages:{Save:"保存"}})
assert.equal(hiddenText.nodeValue,"Save","GalaxySelect must retain canonical hidden option labels for sync()")
assert.equal(translateText('Reset Language to default', {Language:'Sprache','Reset {label} to default':'{label} zurücksetzen'}),'Sprache zurücksetzen')
{
// Poll the language once a minute after a confirmed load; retry quickly only while it cannot be read.
const delays = [], pending = [], listeners = {}
const realSetTimeout = globalThis.setTimeout, realClearTimeout = globalThis.clearTimeout
globalThis.MutationObserver = class { observe() {} disconnect() {} }
globalThis.setTimeout = (fn, ms) => { if (ms === LANGUAGE_RETRY_MS || ms === LANGUAGE_RECHECK_MS) { delays.push(ms); pending.push(fn); return pending.length } return realSetTimeout(fn, ms) }
globalThis.clearTimeout = id => { if (typeof id !== "number" || id > 1000) realClearTimeout(id) }
const visibility = { visibilityState: "visible", addEventListener: (name, fn) => { listeners[name] = fn }, removeEventListener: name => { delete listeners[name] } }
globalThis.document = visibility
const responses = [true, true, false]
let calls = 0
const fetcher = async () => {
calls++
if (!responses.shift()) throw new Error("offline")
return new Response(JSON.stringify({ language: "en", messages: {} }), { status: 200, headers: { "Content-Type": "application/json" } })
}
const root = new Element("main", {}, [text("Home")])
const settle = () => new Promise(resolve => realSetTimeout(resolve, 20))
const stop = startLocalization(root, fetcher)
await settle()
assert.deepEqual(delays, [LANGUAGE_RECHECK_MS], "a confirmed language is rechecked once a minute, not every 2 s")
listeners.visibilitychange()
await settle()
assert.equal(calls, 2, "showing the tab again rechecks at once")
assert.equal(delays.at(-1), LANGUAGE_RECHECK_MS)
pending.at(-1)()
await settle()
assert.equal(calls, 3)
assert.equal(delays.at(-1), LANGUAGE_RETRY_MS, "an unreadable language retries quickly")
stop()
assert.equal(listeners.visibilitychange, undefined)
globalThis.setTimeout = realSetTimeout; globalThis.clearTimeout = realClearTimeout
delete globalThis.document; delete globalThis.MutationObserver
}
@@ -0,0 +1,419 @@
"""galaxy[-N].local is claimed per interface, remembered, and withdrawn on loss."""
import subprocess
import tempfile
import threading
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock, patch
from jeepney.low_level import HeaderFields, MessageType
from openpilot.starpilot.galaxy import mdns
IFADDRS = {'lo': '127.0.0.1', 'ppp0': '10.228.238.20', 'wlan0': '192.168.35.249', 'galaxy0': '172.31.254.1'}
INDEX = {'wlan0': 12, 'eth0': 3, 'galaxy0': 29}
def ifaddr_lookup(sock, name):
if name not in IFADDRS:
raise OSError(19, 'No such device')
return IFADDRS[name]
def index(name):
if name not in INDEX:
raise OSError(19, 'No such device')
return INDEX[name]
class FakeAvahi:
"""Names other devices hold collide; dropped groups read as not established."""
def __init__(self, taken=(), down=0):
self.taken: set[str] = set(taken)
self.down, self.visible = down, set()
self.claims, self.groups, self.freed, self.updates, self.closed = [], {}, [], [], 0
def claim(self, name, entries, group=None):
if self.down:
self.down -= 1
raise ConnectionRefusedError(111, 'avahi down')
self.claims.append((name, entries))
if name in self.taken:
if group is not None:
self.free(group)
return None
if group is not None:
self.updates.append(group)
return group
group = f'/group/{len(self.claims)}'
self.groups[group] = mdns.ESTABLISHED
return group
def state(self, group):
return self.groups[group]
def free(self, group):
self.freed.append(group)
self.groups.pop(group, None)
def close(self):
self.closed += 1
class Reply:
def __init__(self, *body, error=None):
self.body = body
fields = {HeaderFields.error_name: error} if error else {}
self.header = SimpleNamespace(message_type=MessageType.error if error else MessageType.method_return, fields=fields)
class FakeConnection:
"""Scripted avahi D-Bus replies, keyed by member name."""
def __init__(self, states=(mdns.ESTABLISHED,), fail=None, error='org.freedesktop.Avahi.CollisionError', group=('/Client1/EntryGroup1',)):
self.calls, self.states, self.fail, self.error, self.group, self.closed = [], list(states), fail, error, group, False
def send_and_get_reply(self, message, timeout=None):
member = message.header.fields[HeaderFields.member]
self.calls.append((member, message.body))
if member == self.fail:
return Reply('Local name collision', error=self.error)
if member == 'EntryGroupNew':
return Reply(*self.group)
if member == 'GetState':
return Reply(self.states.pop(0) if len(self.states) > 1 else self.states[0])
return Reply()
def close(self):
self.closed = True
class MdnsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.name_file = Path(self.tmp.name) / 'mdns_name'
for name, value in (('_published', None), ('_redirected', False)): # module state the publisher and Redirect share
patcher = patch.object(mdns, name, value)
patcher.start()
self.addCleanup(patcher.stop)
def tearDown(self):
self.tmp.cleanup()
def run_publish(self, avahi, address_seq, check=None, ipv6=lambda name: None, retry=0):
stop = threading.Event()
sequence = iter(address_seq)
def addresses():
try:
value = next(sequence)
except StopIteration:
stop.set()
return {}
if check is not None:
check()
return value
mdns.publish(stop, avahi=avahi, addresses=addresses, ipv6=ipv6, index=index, taken=lambda name, own: name in avahi.visible,
name_file=self.name_file, refresh=0, retry=retry)
def names(self, avahi):
return [name for name, _ in avahi.claims]
def test_interface_addresses_skip_missing_and_non_candidate_interfaces(self):
self.assertEqual(mdns.interface_addresses(ifaddr_lookup), {'wlan0': '192.168.35.249', 'galaxy0': '172.31.254.1'})
self.assertEqual(mdns.interface_addresses(Mock(side_effect=OSError)), {})
with patch.object(subprocess, 'run', side_effect=AssertionError('subprocess')):
mdns.interface_addresses(ifaddr_lookup)
def test_each_interface_answers_with_its_own_address(self):
found = {'wlan0': '10.10.99.177', 'galaxy0': '172.31.254.1', 'eth0': '100.64.0.2'}
entries = mdns.records(found, ipv6=lambda name: 'fe80::1' if name == 'wlan0' else None, index=index)
self.assertEqual(entries, ((12, mdns.PROTO_INET, '10.10.99.177'), (12, mdns.PROTO_INET6, 'fe80::1'),
(29, mdns.PROTO_INET, '172.31.254.1')))
self.assertEqual(mdns.records({'wlan0': '10.10.99.177', 'galaxy0': '172.31.254.1'}, ipv6=lambda name: None,
index=lambda name: index(name) if name == 'galaxy0' else (_ for _ in ()).throw(OSError())),
((29, mdns.PROTO_INET, '172.31.254.1'),))
def test_first_device_gets_galaxy_local(self):
avahi, seen = FakeAvahi(), []
self.run_publish(avahi, [{'wlan0': '192.168.1.5', 'galaxy0': '172.31.254.1'}] * 2,
check=lambda: seen.append(mdns.published_record()))
self.assertEqual(self.names(avahi), ['galaxy.local'])
self.assertEqual(seen[-1], ('galaxy.local', ('192.168.1.5', '172.31.254.1')))
self.assertIsNone(mdns.published_record())
self.assertEqual(avahi.freed, ['/group/1'])
self.assertEqual(avahi.closed, 1)
self.assertEqual(self.name_file.read_text().strip(), 'galaxy.local')
def test_collision_walks_to_next_name_and_remembers_it(self):
avahi = FakeAvahi(taken={'galaxy.local'})
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy-2.local'])
self.assertEqual(mdns.load_name(self.name_file), 'galaxy-2.local')
# Next boot keeps galaxy-2 even when galaxy.local is free.
avahi = FakeAvahi()
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy-2.local'])
def test_remembered_name_taken_falls_back_to_first_free(self):
mdns.save_name('galaxy-2.local', self.name_file)
avahi = FakeAvahi(taken={'galaxy-2.local'})
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy-2.local', 'galaxy.local'])
self.assertEqual(mdns.load_name(self.name_file), 'galaxy.local')
def test_hotspot_coming_up_republishes_same_name_with_its_address(self):
avahi = FakeAvahi()
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}, {'wlan0': '192.168.1.5', 'galaxy0': '172.31.254.1'}])
self.assertEqual(avahi.claims, [('galaxy.local', ((12, 0, '192.168.1.5'),)),
('galaxy.local', ((12, 0, '192.168.1.5'), (29, 0, '172.31.254.1')))])
self.assertEqual(avahi.updates, ['/group/1'], 'the established group is republished in place')
def test_network_switch_keeps_the_name_even_if_our_old_address_still_answers(self):
avahi = FakeAvahi()
asked = []
def stale_answer(name, own):
asked.append(name)
return name == 'galaxy.local' and '10.10.99.177' not in own # avahi still returns our old work address
stop, steps = threading.Event(), iter([{'wlan0': '10.10.99.177'}, {'wlan0': '172.20.10.4'}])
def addresses():
try:
return next(steps)
except StopIteration:
stop.set()
return {}
mdns.publish(stop, avahi=avahi, addresses=addresses, ipv6=lambda name: None, index=index, taken=stale_answer,
name_file=self.name_file, refresh=0, retry=0)
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy.local'])
self.assertEqual(asked, ['galaxy.local'], 'an in-place update never re-checks a name we hold')
self.assertEqual(mdns.load_name(self.name_file), 'galaxy.local')
def test_our_earlier_addresses_never_count_as_another_device(self):
run = Mock(return_value=SimpleNamespace(stdout='galaxy.local\t10.10.99.177\n'))
avahi = FakeAvahi()
taken = lambda name, own: mdns.held_elsewhere(name, own, run) # noqa: E731
entries = ((12, 0, '172.20.10.4'),)
self.assertEqual(mdns._claim(avahi, entries, None, threading.Event(), taken, {'10.10.99.177'})[0], 'galaxy.local')
self.assertEqual(mdns._claim(FakeAvahi(), entries, None, threading.Event(), taken)[0], 'galaxy-2.local')
def test_failed_in_place_update_falls_back_to_a_fresh_claim(self):
avahi = FakeAvahi()
def lose_name_on_update():
if len(avahi.claims) == 1:
avahi.taken.add('galaxy.local')
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}, {'wlan0': '192.168.1.9'}], check=lose_name_on_update)
# update collides, the fresh claim probes galaxy.local once more, then moves on
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy.local', 'galaxy.local', 'galaxy-2.local'])
def test_lost_name_is_reclaimed(self):
avahi = FakeAvahi()
def collide_later():
if len(avahi.claims) == 1 and avahi.groups:
avahi.groups['/group/1'] = 3 # another device won the name
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}] * 3, check=collide_later)
self.assertEqual(len(avahi.claims), 2)
def test_names_answered_elsewhere_are_skipped_without_probing(self):
avahi = FakeAvahi()
avahi.visible = {'galaxy.local'}
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy-2.local'])
def test_held_elsewhere_ignores_our_own_addresses(self):
def run(out):
return Mock(return_value=SimpleNamespace(stdout=out))
own = {'192.168.1.6', '172.31.254.1'}
self.assertTrue(mdns.held_elsewhere('galaxy.local', own, run('galaxy.local\t192.168.1.7\n')))
self.assertFalse(mdns.held_elsewhere('galaxy.local', own, run('galaxy.local\t172.31.254.1\n')))
self.assertFalse(mdns.held_elsewhere('galaxy.local', own, run('Failed to resolve host name')))
self.assertFalse(mdns.held_elsewhere('galaxy.local', own, Mock(side_effect=subprocess.TimeoutExpired('x', 1))))
def test_all_names_taken_publishes_nothing(self):
avahi = FakeAvahi(taken=set(mdns.NAMES))
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}])
self.assertEqual(len(avahi.claims), len(mdns.NAMES))
self.assertIsNone(mdns.load_name(self.name_file))
def test_no_lan_address_publishes_nothing(self):
avahi = FakeAvahi()
self.run_publish(avahi, [{}, {'ppp0': '10.228.238.20'}])
self.assertEqual(avahi.claims, [])
def test_avahi_down_logs_once_and_retries(self):
logged = []
avahi = FakeAvahi(down=3)
with patch.object(mdns, '_log', side_effect=lambda message, warning=True: logged.append(message)):
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}] * 5)
self.assertEqual(sum('avahi unavailable' in m for m in logged), 1)
self.assertEqual(self.names(avahi), ['galaxy.local'])
self.assertIn('published galaxy.local on wlan0', logged)
self.assertFalse(any('192.168.1.5' in m for m in logged), 'LAN addresses stay out of swaglog')
def test_retry_waits_after_failure(self):
avahi = FakeAvahi(down=1)
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}] * 3, retry=3600)
self.assertEqual(avahi.claims, [])
def test_stop_wakes_publisher_promptly(self):
stop = threading.Event()
worker = threading.Thread(target=mdns.publish, args=(stop,), kwargs={
'avahi': FakeAvahi(), 'addresses': dict, 'taken': lambda name, own: False, 'name_file': self.name_file, 'refresh': 60})
worker.start()
stop.set()
worker.join(2)
self.assertFalse(worker.is_alive())
def test_avahi_claim_publishes_every_record_then_waits_for_probe(self):
connection = FakeConnection(states=[1, mdns.ESTABLISHED])
avahi = mdns.Avahi(connect=lambda: connection)
entries = ((12, 0, '10.10.99.177'), (12, 1, 'fe80::1'), (29, 0, '172.31.254.1'))
self.assertEqual(avahi.claim('galaxy.local', entries), '/Client1/EntryGroup1')
added = [body for member, body in connection.calls if member == 'AddAddress']
self.assertEqual(added, [(n, p, mdns.PUBLISH_NO_REVERSE, 'galaxy.local', a) for n, p, a in entries])
self.assertEqual([m for m, _ in connection.calls].count('Commit'), 1)
def test_avahi_claim_frees_group_on_collision_or_error(self):
for connection in (FakeConnection(states=[3]), FakeConnection(fail='AddAddress')):
avahi = mdns.Avahi(connect=lambda c=connection: c)
self.assertIsNone(avahi.claim('galaxy.local', ((12, 0, '10.10.99.177'),)))
self.assertEqual(connection.calls[-1][0], 'Free')
def test_avahi_other_errors_are_failures_not_taken_names(self):
connection = FakeConnection(fail='AddAddress', error='org.freedesktop.Avahi.NotPermittedError')
with self.assertRaises(mdns.AvahiError):
mdns.Avahi(connect=lambda: connection).claim('galaxy.local', ((12, 0, '10.10.99.177'),))
self.assertEqual(connection.calls[-1][0], 'Free')
def test_malformed_avahi_reply_is_an_error(self):
for group in ((), (7,)):
with self.assertRaises(mdns.AvahiError):
mdns.Avahi(connect=lambda g=group: FakeConnection(group=g)).claim('galaxy.local', ((12, 0, '10.10.99.177'),))
def test_claim_stops_waiting_for_probe_on_stop(self):
stop = threading.Event()
stop.set()
connection = FakeConnection(states=[1])
self.assertIsNone(mdns.Avahi(connect=lambda: connection, stopped=stop.is_set).claim('galaxy.local', ((12, 0, '10.10.99.177'),)))
self.assertEqual([m for m, _ in connection.calls].count('GetState'), 1)
avahi = FakeAvahi()
self.assertEqual(mdns._claim(avahi, ((12, 0, '10.10.99.177'),), None, stop, lambda name, own: False), (None, None))
self.assertEqual(avahi.claims, [])
def test_claim_with_our_group_resets_it_in_place(self):
connection = FakeConnection()
group = mdns.Avahi(connect=lambda: connection).claim('galaxy.local', ((12, 0, '172.20.10.4'),), group='/Client1/EntryGroup1')
self.assertEqual(group, '/Client1/EntryGroup1')
self.assertEqual([m for m, _ in connection.calls][:3], ['Reset', 'AddAddress', 'Commit'])
self.assertNotIn('EntryGroupNew', [m for m, _ in connection.calls])
self.assertNotIn('Free', [m for m, _ in connection.calls])
def test_avahi_reconnects_after_connection_loss(self):
connections = [Mock(send_and_get_reply=Mock(side_effect=ConnectionResetError())), FakeConnection()]
avahi = mdns.Avahi(connect=lambda: connections.pop(0))
with self.assertRaises(ConnectionResetError):
avahi.state('/group')
self.assertIsNone(avahi.connection)
self.assertEqual(avahi.state('/group'), mdns.ESTABLISHED)
def test_bad_remembered_name_ignored(self):
self.name_file.write_text('evil.example\n')
self.assertIsNone(mdns.load_name(self.name_file))
def test_redirect_targets_only_own_addresses_and_resyncs_on_change(self):
calls = []
def run(cmd, **kwargs):
calls.append(cmd[7:]) # drop sudo -n iptables -w 2 -t nat
return SimpleNamespace(returncode=1 if cmd[7] == '-C' else 0)
redirect = mdns.Redirect(8082, run=run, which=lambda name: f'/usr/sbin/{name}')
redirect.sync(['192.168.35.249', '172.31.254.1'])
self.assertIn(['-I', 'PREROUTING', '-p', 'tcp', '--dport', '80', '-j', 'GALAXY_HTTP'], calls)
self.assertEqual([c for c in calls if c[0] == '-A'], [
['-A', 'GALAXY_HTTP', '-d', '172.31.254.1', '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', '8082'],
['-A', 'GALAXY_HTTP', '-d', '192.168.35.249', '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', '8082']])
calls.clear()
redirect.sync(['172.31.254.1', '192.168.35.249'])
self.assertEqual(calls, []) # unchanged set: no sudo on the poll
redirect.sync(['192.168.35.50', '100.64.0.1'])
self.assertEqual(calls, [['-F', 'GALAXY_HTTP'],
['-A', 'GALAXY_HTTP', '-d', '192.168.35.50', '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', '8082']])
def test_redirect_failure_is_logged_not_retried_every_poll(self):
run = Mock(side_effect=subprocess.TimeoutExpired('sudo', 5))
redirect = mdns.Redirect(8082, run=run, which=lambda name: '/usr/sbin/iptables')
redirect.sync(['192.168.35.249'])
redirect.sync(['192.168.35.249'])
self.assertEqual(run.call_count, 1) # tried once, not on every poll
mdns.Redirect(8082, run=run, which=lambda name: None).sync(['192.168.35.249'])
self.assertEqual(run.call_count, 1)
def test_link_local_reads_proc(self):
proc = Path(self.tmp.name) / 'if_inet6'
proc.write_text('\n'.join(['fe80000000000000020af5fffe66c88a 0c 40 20 80 wlan0',
'2001db80000000000000000000000001 0c 40 00 00 wlan0',
'fe800000000000000000000000000001 1d 40 20 80 galaxy0']) + '\n')
self.assertEqual(mdns.link_local('wlan0', proc), 'fe80::20a:f5ff:fe66:c88a')
self.assertIsNone(mdns.link_local('eth0', proc))
self.assertIsNone(mdns.link_local('wlan0', Path(self.tmp.name) / 'missing'))
def test_published_url_drops_the_port_only_while_port_80_redirects(self):
with patch.object(mdns, '_published', None):
self.assertIsNone(mdns.published_url(8082))
with patch.object(mdns, '_published', ('galaxy-2.local', ('192.168.1.5',))):
run = Mock(return_value=SimpleNamespace(returncode=0))
redirect = mdns.Redirect(8082, run=run, which=lambda name: '/usr/sbin/iptables')
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
redirect.sync(['192.168.1.5'])
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local/')
redirect.close()
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
with patch.object(mdns, '_log'):
mdns.Redirect(8082, run=Mock(side_effect=OSError('denied')), which=lambda name: '/usr/sbin/iptables').sync(['192.168.1.5'])
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
def test_redirect_close_removes_rules_once(self):
calls = []
redirect = mdns.Redirect(8082, run=lambda cmd, **kw: calls.append(cmd[7:]) or SimpleNamespace(returncode=0),
which=lambda name: '/usr/sbin/iptables')
redirect.close()
self.assertEqual(calls, []) # never installed: nothing to remove
redirect.sync(['192.168.35.249'])
calls.clear()
redirect.close()
self.assertEqual([c[0] for c in calls], ['-D', '-F', '-X'])
calls.clear()
redirect.close()
self.assertEqual(calls, [])
def test_oversized_name_file_ignored(self):
self.name_file.write_text('galaxy.local' + ' ' * 100)
self.assertIsNone(mdns.load_name(self.name_file))
def test_unexpected_crash_is_logged_and_cleans_up(self):
redirect = Mock()
with patch.object(mdns, 'Redirect', return_value=redirect), \
patch.object(mdns, 'publish', side_effect=RuntimeError('boom')), \
patch('openpilot.common.swaglog.cloudlog.exception') as logged:
mdns.run(threading.Event(), 8082)
logged.assert_called_once()
redirect.close.assert_called_once()
if __name__ == '__main__':
unittest.main()
@@ -6,6 +6,7 @@ import { GxNotice } from "./notice.js"
export function validLocalAccess(value) {
if (!value || typeof value.available !== "boolean" || typeof value.reason !== "string" || value.reason.length > 1024 ||
!Array.isArray(value.addresses) || value.addresses.length > 32 || value.available !== (value.addresses.length > 0)) return false
if (value.name !== undefined && (typeof value.name !== "string" || value.name !== "" && !/^http:\/\/galaxy(-[2-9])?\.local(:\d{1,5})?\/$/.test(value.name))) return false
return value.addresses.every(address => {
if (!address || !["interface", "label", "url"].every(key => typeof address[key] === "string" && address[key].length > 0 && address[key].length <= 512)) return false
try {
@@ -65,7 +66,8 @@ export const LocalAccess = {
<GxNotice v-if="state.error" tone="danger">{{ state.error }}</GxNotice>
<template v-else-if="state.data?.available">
<p>Connect your phone to the Galaxy hotspot or the same network as your comma, then open an address below. No Internet or Galaxy password needed.</p>
<ul class="gx-stack"><li v-for="address in state.data.addresses" :key="address.interface + address.url"><a :href="address.url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">{{ address.label }} · {{ address.url }}</a></li></ul>
<ul class="gx-stack"><li v-if="state.data.name"><a :href="state.data.name" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">This comma · {{ state.data.name }}</a></li><li v-for="address in state.data.addresses" :key="address.interface + address.url"><a :href="address.url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">{{ address.label }} · {{ address.url }}</a></li></ul>
<p v-if="state.data.name" class="gx-note">The first comma on a network is galaxy.local; the next ones become galaxy-2.local, galaxy-3.local, and so on.</p>
<p class="gx-note">Use the full http:// address and bookmark it. Allow local-network access if prompted. Your Firestar Link uses Internet instead.</p>
</template>
<p v-else-if="state.data" class="gx-note" role="status">{{ state.data.reason || 'The comma has no local network address available.' }}</p>
@@ -88,6 +88,10 @@ export function localizeDocument(root, { language, messages }, records = new Wea
return records
}
// Recheck the language each minute and when shown; retry quickly only while it cannot be read.
export const LANGUAGE_RECHECK_MS = 60000
export const LANGUAGE_RETRY_MS = 2000
export function startLocalization(root = document.body, fetcher = fetch) {
let state = { language: "en", messages: {} }, stopped = false, timer, scheduled = false, generation = 0, request
const records = new WeakMap()
@@ -113,21 +117,28 @@ export function startLocalization(root = document.body, fetcher = fetch) {
request?.abort()
const current = ++generation
request = new AbortController()
let delay = LANGUAGE_RETRY_MS
try {
const next = await requestJson(`./api/localization?language=${encodeURIComponent(state.language)}`,
{ fetcher, timeout: 4000, request: { signal: request.signal } })
if (!stopped && current === generation && typeof next.language === "string" && next.messages && typeof next.messages === "object") {
state = next
apply()
delay = LANGUAGE_RECHECK_MS
}
} catch { /* Keep the last confirmed language during connection loss. */ }
if (!stopped && current === generation) timer = setTimeout(refresh, 2000)
if (!stopped && current === generation) timer = setTimeout(refresh, delay)
}
function shown() {
if (globalThis.document?.visibilityState === "visible") refresh()
}
apply()
globalThis.addEventListener?.("galaxy-language-changed", refresh)
globalThis.document?.addEventListener?.("visibilitychange", shown)
refresh()
return () => {
stopped = true; generation++; request?.abort(); clearTimeout(timer); observer.disconnect()
globalThis.removeEventListener?.("galaxy-language-changed", refresh)
globalThis.document?.removeEventListener?.("visibilitychange", shown)
}
}
+25 -6
View File
@@ -24,6 +24,7 @@ GALAXY_ICON = "icons_mici/settings/galaxy.png"
REMOTE_URL = re.compile(r"https://galaxy\.firestar\.link/[A-Za-z0-9]{16}\Z")
LOCAL_PORT = 8082
LOCAL_ORIGIN = f"http://127.0.0.1:{LOCAL_PORT}"
LOCAL_NAME = re.compile(r"http://galaxy(-[2-9])?\.local(:8082)?/\Z")
@dataclass(frozen=True)
@@ -33,6 +34,7 @@ class RemoteStatus:
available: bool = False
legacy: bool = False
error: str = ""
name: str = ""
def _local_api(path: str, *, cookie: str = "", payload: dict | None = None, deadline: float) -> tuple[int, dict, str]:
@@ -89,7 +91,16 @@ def _remote_operation(action: str, password: str = "") -> RemoteStatus:
if paired and (type(url) is not str or REMOTE_URL.fullmatch(url) is None):
return RemoteStatus(error="Galaxy pairing status is unavailable")
return RemoteStatus(paired, url if paired and isinstance(url, str) else "", result.get("tunnelClientAvailable") is True,
result.get("legacyPairingAvailable") is True)
result.get("legacyPairingAvailable") is True, name=_local_name(cookie, deadline))
def _local_name(cookie: str, deadline: float) -> str:
try:
code, result, _ = _local_api("/api/local-access", cookie=cookie, deadline=deadline)
except (OSError, ValueError, http.client.HTTPException):
return ""
name = result.get("name") if code == 200 else None
return name if type(name) is str and LOCAL_NAME.fullmatch(name) else ""
def connection_url(address: str) -> str | None:
@@ -134,9 +145,9 @@ class GalaxyAccessFlow:
self._remote_future = None
try:
updated = future.result()
self.remote = replace(self.remote, error=updated.error) if updated.error and self._remote_action == "status" else updated
self.remote = replace(self.remote, error=updated.error, name="") if updated.error and self._remote_action == "status" else updated
except (OSError, ValueError, RuntimeError, http.client.HTTPException):
self.remote = replace(self.remote, error="Local Galaxy is unavailable") if self._remote_action == "status" else \
self.remote = replace(self.remote, error="Local Galaxy is unavailable", name="") if self._remote_action == "status" else \
RemoteStatus(error="Local Galaxy is unavailable")
if self._remote_future is None and time.monotonic() >= self._remote_next_check:
self._submit("status")
@@ -286,12 +297,17 @@ class GalaxyConnectionView(Widget):
message = ("Or open this address on the same network:" if self._url else
"Connect to Wi-Fi to show the local address.")
rl.draw_text_ex(font, message, rl.Vector2(left, rect.y + 680), 36, 0, rl.LIGHTGRAY)
y = rect.y + 745
if remote.name:
rl.draw_text_ex(font, remote.name, rl.Vector2(left, y), 44, 0, rl.WHITE)
y += 60
if self._url:
rl.draw_text_ex(font, self._url, rl.Vector2(left, rect.y + 745), 44, 0, rl.WHITE)
rl.draw_text_ex(font, self._url, rl.Vector2(left, y), 44, 0, rl.WHITE)
y += 65
if self._qr is not None:
rl.draw_texture_pro(self._qr, rl.Rectangle(0, 0, self._qr.width, self._qr.height),
rl.Rectangle(rect.x + rect.width - 420, rect.y + 610, 220, 220), rl.Vector2(0, 0), 0, rl.WHITE)
rl.draw_text_ex(font, "No password is needed on this network.", rl.Vector2(left, rect.y + 810), 36, 0, rl.LIGHTGRAY)
rl.draw_text_ex(font, "No password is needed on this network.", rl.Vector2(left, max(y, rect.y + 810)), 36, 0, rl.LIGHTGRAY)
self._close.render(rl.Rectangle(rect.x + rect.width - 430, rect.y + rect.height - 165, 300, 110))
def __del__(self):
@@ -318,6 +334,7 @@ class GalaxyConnectionPage:
self._remote_url: str | None = None
self._remote_qr = QR("", width=300)
self._address = GreyBigButton("local Galaxy • no password", "connect to Wi-Fi")
self._name = GreyBigButton("this comma's name", "")
self._remote_address = GreyBigButton("remote Galaxy", "checking pairing")
self._remote_state = GreyBigButton("remote connection", "")
self._pair = BigButton("pair with Galaxy", "1. set a password", gui_app.texture(GALAXY_ICON, 64, 64))
@@ -325,7 +342,7 @@ class GalaxyConnectionPage:
self._unpair = BigButton("unpair remote Galaxy", "", gui_app.texture(GALAXY_ICON, 64, 64))
self._unpair.set_click_callback(self._confirm_unpair)
self._scroller.add_widgets([self._pair, self._remote_qr, self._remote_address, self._remote_state,
self._unpair, self._qr, self._address])
self._unpair, self._name, self._qr, self._address])
def _submit_password(self, password: str) -> None:
flow.pair(password)
@@ -358,6 +375,8 @@ class GalaxyConnectionPage:
self._set_qr(self._qr, url or "")
self._address.set_value(url or "connect to Wi-Fi to show the local address")
remote = flow.update_remote()
self._name.set_value(remote.name)
self._name.set_visible(bool(remote.name))
self._remote_url = remote.url
self._set_qr(self._remote_qr, remote.url)
self._remote_address.set_value(remote.url if remote.paired else "not paired • set a password")
@@ -7,6 +7,7 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock, patch
from openpilot.starpilot.galaxy import mdns
from openpilot.starpilot.galaxy.access import AccessStatus, GalaxyAccessOwner
from openpilot.starpilot.galaxy.remote import RemotePairing
from openpilot.starpilot.galaxy.server import make_server
@@ -30,7 +31,10 @@ class TestGalaxyConnection(unittest.TestCase):
try:
with patch.object(galaxy_access, "LOCAL_PORT", server.server_port), \
patch.object(galaxy_access, "LOCAL_ORIGIN", f"http://127.0.0.1:{server.server_port}"):
self.assertFalse(galaxy_access._remote_operation("status").paired)
with patch.object(mdns, "_published", ("galaxy-2.local", ("127.0.0.1",))), patch.object(mdns, "_redirected", True):
status = galaxy_access._remote_operation("status")
self.assertFalse(status.paired)
self.assertEqual(status.name, "http://galaxy-2.local/")
paired = galaxy_access._remote_operation("pair", " password123 ")
self.assertTrue(paired.paired)
self.assertTrue(galaxy_access.REMOTE_URL.fullmatch(paired.url))
@@ -172,11 +176,43 @@ class TestGalaxyConnection(unittest.TestCase):
texts = [call.args[1] for call in draw.call_args_list]
self.assertIn(url, texts)
self.assertIn("No password is needed on this network.", texts)
self.assertNotIn("http://galaxy.local/", texts)
self.assertLess(texts.index("Choose a password, then pair your comma with Galaxy."), texts.index("Local network"))
self.assertEqual((view._close.text, view._pair.text, view._unpair.text),
("Close", "Set password & pair", "Unpair remote Galaxy"))
self.assertEqual(owner.mock_calls, [])
def test_large_page_shows_this_commas_name_above_the_address(self):
class Button(Widget):
def __init__(self, text, callback, **kwargs):
super().__init__()
def _render(self, rect):
pass
flow = GalaxyAccessFlow(Mock(), lambda: True)
url = "http://192.168.1.111:8082/#/"
with patch("openpilot.system.ui.widgets.button.Button", Button), \
patch.object(flow, "_url", return_value=url), \
patch.object(flow, "update_remote", return_value=RemoteStatus(name="http://galaxy-2.local/")), \
patch("openpilot.starpilot.ui.galaxy_access.make_texture", return_value=None) as qr, \
patch("openpilot.starpilot.ui.galaxy_access.gui_app.font"), \
patch.object(rl, "draw_rectangle_rec"), patch.object(rl, "draw_text_ex") as draw:
view = GalaxyConnectionView(flow)
view._update_state()
view._render(rl.Rectangle(0, 0, 2160, 1080))
qr.assert_called_once_with(url) # the QR stays on the IP, which every phone can open
texts = [call.args[1] for call in draw.call_args_list]
self.assertLess(texts.index("http://galaxy-2.local/"), texts.index(url))
def test_local_name_accepts_only_galaxy_names(self):
for name, expected in (("http://galaxy.local/", True), ("http://galaxy-9.local:8082/", True), ("http://evil.local/", False),
("http://galaxy.local/x", False), ("https://galaxy.local/", False)):
with self.subTest(name=name), patch.object(galaxy_access, "_local_api", return_value=(200, {"name": name}, "")):
self.assertEqual(galaxy_access._local_name("c", 0), name if expected else "")
with patch.object(galaxy_access, "_local_api", side_effect=TimeoutError):
self.assertEqual(galaxy_access._local_name("c", 0), "")
def test_compact_page_has_local_and_remote_views_without_credential_access(self):
class Scroller:
def __init__(self):
@@ -207,10 +243,12 @@ class TestGalaxyConnection(unittest.TestCase):
self.assertEqual(button.call_args_list[0].args, ("local Galaxy • no password", "connect to Wi-Fi"))
self.assertEqual([call.args for call in button.call_args_list], [
("local Galaxy • no password", "connect to Wi-Fi"),
("this comma's name", ""),
("remote Galaxy", "checking pairing"),
("remote connection", "")])
self.assertEqual(page._scroller.add_widgets.call_args.args[0],
[page._pair, page._remote_qr, page._remote_address, page._remote_state, page._unpair, page._qr, page._address])
[page._pair, page._remote_qr, page._remote_address, page._remote_state, page._unpair, page._name, page._qr, page._address])
page._name.set_visible.assert_called_with(False)
with patch("openpilot.starpilot.ui.galaxy_access.gui_app.push_widget") as pushed:
page._enter_password()
self.assertIs(prompt.call_args.kwargs["password_mode"], True)
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "1c0e5979b7f1949b9844ebcfec50b6c019b29be32450eec134d6bb6225bb4432", "schema_version": 1}
{"protected_inventory_sha256": "762f2c9966cf181e93d588252871712e17528e9ad7751e79015ce9971a614489", "schema_version": 1}