diff --git a/scripts/netcore/netctl.py b/scripts/netcore/netctl.py index 82062f1..03eb860 100644 --- a/scripts/netcore/netctl.py +++ b/scripts/netcore/netctl.py @@ -138,6 +138,22 @@ def network_services(): return [l for l in out[1:] if l and not l.startswith("*")] +def active_services(): + """Hardware services that carry traffic right now: Wi-Fi or a wired adapter (en*) with + status active. Touching the others — «iPhone USB», Thunderbolt Bridge, VPN services — + made macOS re-check them and offer the iPhone's hotspot over and over.""" + order = subprocess.run(["/usr/sbin/networksetup", "-listnetworkserviceorder"], + capture_output=True, text=True, timeout=10).stdout + out = [] + for name, port, dev in re.findall(r"\(\d+\) (.+)\n\(Hardware Port: ([^,]*), Device: ([^)]*)\)", order): + if not re.fullmatch(r"en\d+", dev) or "iphone" in (name + port).lower(): + continue + status = subprocess.run(["/sbin/ifconfig", dev], capture_output=True, text=True, timeout=5).stdout + if "status: active" in status: + out.append(name.strip()) + return out + + def dns_of(service): out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service], capture_output=True, text=True, timeout=10).stdout.splitlines() @@ -156,11 +172,15 @@ def dns_to_core(): backup = json.load(f) except (OSError, ValueError): backup = {} + active = set(active_services()) for svc in network_services(): cur = dns_of(svc) - if cur != [CORE_DNS]: - backup[svc] = cur - set_dns(svc, [CORE_DNS]) + if svc in active: + if cur != [CORE_DNS]: + backup[svc] = cur + set_dns(svc, [CORE_DNS]) + elif cur == [CORE_DNS]: # set by an older version: give it back + set_dns(svc, [x for x in backup.pop(svc, []) if x != CORE_DNS]) fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "w") as f: json.dump(backup, f) @@ -420,6 +440,14 @@ def cmd_rebind(_): done.append(prov) except Exception: pass + # A new network may run on another adapter (Wi-Fi → Ethernet): its DNS goes into the + # core too, while capture is on. + try: + with open(os.path.join(CORE, "tun.json")) as f: + if json.load(f).get("on", True): + dns_to_core() + except (OSError, ValueError): + pass return {"ok": True, "rebound": done}