Galaxy: Open by galaxy.local on Every Network, Including the Hotspot

This commit is contained in:
Danny
2026-11-23 09:36:23 -08:00
parent de8f420d95
commit 6d5d6c249f
7 changed files with 776 additions and 4 deletions
@@ -207,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)
+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__':
+347
View File
@@ -0,0 +1,347 @@
"""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
def published_record():
return _published
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):
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 = wanted
except (OSError, subprocess.SubprocessError) as error:
self.applied = wanted # 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):
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):
"""The committed group once avahi has probed the name, or None if another device holds it."""
group = self.first('/', SERVER, 'EntryGroupNew', str)
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):
own = {address for _, _, address in entries}
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 = load_name(name_file)
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):
if group is not None:
avahi.free(group)
group, _published, entries = None, None, wanted
if wanted:
name = None
try:
name, group = _claim(avahi, wanted, remembered, stop, taken)
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
_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
@@ -270,3 +272,22 @@ def test_drain_turns_away_requests_still_waiting_for_capacity(server, monkeypatc
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)
@@ -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,344 @@
"""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, self.down, self.visible = set(taken), down, set()
self.claims, self.groups, self.freed, self.closed = [], {}, [], 0
def claim(self, name, entries):
if self.down:
self.down -= 1
raise ConnectionRefusedError(111, 'avahi down')
self.claims.append((name, entries))
if name in self.taken:
return None
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'
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.freed[0], '/group/1')
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_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_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()
@@ -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)
}
}