#!/usr/bin/python3 -I
"""Session-owned Linux routing for new sockets of explicitly launched apps."""
import argparse
import contextlib
import errno
import fcntl
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import select
import selectors
import signal
import socket
import stat
import struct
import subprocess
import sys
import time

ROOT = Path('/run/obfusgated-route-session')
CGROUPS = Path('/sys/fs/cgroup')
TOOLS = {name: next((base + name for base in ('/usr/sbin/', '/usr/bin/')
                     if os.access(base + name, os.X_OK)), '/usr/sbin/' + name)
         for name in ('ip', 'nft', 'iptables', 'ip6tables')}
DIRECT_APPROVED = '0x4f470202'
LEASE_SECONDS = 4
MAX_SCOPES = 128
QUARANTINE = "0x4f470200"
WEBSITE_UNIT_PREFIX = 'app-obfusgatedweb-'
UNIT = re.compile(r'app-obfusgated(?:route|web)-[0-9a-f]{32}\.scope\Z')
IFNAME = re.compile(r'[a-zA-Z0-9_.-]{1,15}\Z')
MODES = {'vpn': 'vpn', 'direct': 'direct', 'website-browser': 'vpn', 'website-proxy': 'direct'}


class RoutingError(Exception):
    pass


def run(tool, args, data=None):
    try:
        result = subprocess.run([TOOLS[tool], *args], input=data, text=True,
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                timeout=3, env={'PATH': '/usr/sbin:/usr/bin', 'LC_ALL': 'C'})
    except (OSError, subprocess.TimeoutExpired) as error:
        raise RoutingError('Cannot run ' + tool) from error
    if result.returncode:
        raise RoutingError(tool + ': ' + result.stderr.strip()[:400])
    return result.stdout


def nft(script):
    return run('nft', ['-f', '-'], script + '\n')


def write_state(path, value):
    temp = path.with_suffix('.tmp')
    with temp.open('w', encoding='utf-8') as output:
        os.fchmod(output.fileno(), 0o600)
        json.dump(value, output)
    temp.replace(path)


def scope_of(pid, uid):
    unified = [line[3:] for line in Path(f'/proc/{pid}/cgroup').read_text().splitlines()
               if line.startswith('0::')]
    if len(unified) != 1:
        raise RoutingError('A unified cgroup v2 session is required')
    scope = unified[0]
    if not managed_scope(scope, uid):
        raise RoutingError('The requesting process is outside its managed launch scope')
    return scope


def managed_scope(scope, uid):
    prefix = f'/user.slice/user-{uid}.slice/user@{uid}.service/'
    parts = scope.split('/')
    return (scope.startswith(prefix) and len(scope) <= 230 and
            re.fullmatch(r'/[A-Za-z0-9_.@:/-]+', scope) is not None and
            UNIT.fullmatch(parts[-1]) is not None and
            all(part not in ('', '.', '..') for part in parts[1:]))


def populated(scope):
    try:
        return 'populated 1' in (CGROUPS / scope.lstrip('/') / 'cgroup.events').read_text().splitlines()
    except OSError as error:
        # kernfs can deactivate this cgroup after open and before read.
        if error.errno in (errno.ENOENT, errno.ENODEV):
            return False
        raise


def ipv4(value):
    address = ipaddress.IPv4Address(value)
    if address.is_unspecified or address.is_multicast or address.is_loopback or int(address) == 0xffffffff:
        raise RoutingError('Invalid session network address')
    return str(address)


def link_info(name):
    if not IFNAME.fullmatch(name) or name == 'lo' or name.startswith('-'):
        raise RoutingError('Invalid session interface name')
    info, = json.loads(run('ip', ['-j', '-4', 'addr', 'show', 'dev', name]))
    if 'UP' not in info['flags']:
        raise RoutingError('Session network interface is down')
    return info['ifindex'], [(item['local'], item['prefixlen']) for item in info['addr_info']
                             if item['family'] == 'inet']


def verify_links(args):
    if args.tunnel == args.uplink:
        raise RoutingError('The VPN and physical uplink use the same interface')
    tun, addresses = link_info(args.tunnel)
    # Reject a guessed/foreign ordinary link supplied in place of the TUN.
    detail, = json.loads(run('ip', ['-d', '-j', 'link', 'show', 'dev', args.tunnel]))
    info = detail.get('linkinfo', {})
    if info.get('info_kind') != 'tun' or info.get('info_data', {}).get('type') != 'tun' or not addresses:
        raise RoutingError('The session tunnel is unavailable')
    uplink, physical_addresses = link_info(args.uplink)
    matching = [prefix for source, prefix in physical_addresses if source == args.source]
    if len(matching) != 1:
        raise RoutingError('The physical source address changed')
    return tun, uplink, ipv4(addresses[0][0]), matching[0]


def undo(journal):
    # Remove classifiers last, after grants are closed and no managed descendants remain.
    pending = []
    for tool, args in reversed(journal['undo']):
        try:
            run(tool, args)
        except RoutingError as error:
            message = str(error)
            absent = ('No such file or directory', 'No such process', 'Cannot find device',
                      'does a matching rule exist in that chain', 'No chain/target/match by that name')
            if not any(text in message for text in absent):
                pending.append((tool, args))
    return list(reversed(pending))


def revoke(journal):
    try:
        nft('flush set inet ' + journal['table'] + ' live')
    except RoutingError as error:
        if 'No such file or directory' not in str(error):
            raise


def change_source_validation(index, value):
    # RTM_NEWLINK / IFLA_AF_SPEC / AF_INET / IFLA_INET_CONF /
    # IPV4_DEVCONF_SRC_VMARK. Update only this interface's one IPv4 attribute.
    # The service owns link configuration via NETLINK_ROUTE.
    def attr(kind, payload):
        return struct.pack('=HH', 4 + len(payload), kind) + payload

    conf = attr(24, struct.pack('=I', value))
    af = attr(26, attr(socket.AF_INET, attr(1, conf)))
    link = struct.pack('=BBHiII', socket.AF_UNSPEC, 0, 0, index, 0, 0)
    message = struct.pack('=IHHII', 16 + len(link) + len(af), 16, 5, 1, 0) + link + af
    with socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, socket.NETLINK_ROUTE) as netlink:
        netlink.settimeout(2)
        netlink.sendto(message, (0, 0))
        ack, sender = netlink.recvfrom(4096)
        if sender[0] != 0 or len(ack) < 20 or struct.unpack_from('=H', ack, 4)[0] != 2:
            raise RoutingError('Unexpected interface configuration reply')
        error, = struct.unpack_from('=i', ack, 16)
        if error:
            raise OSError(-error, os.strerror(-error))


def restore_source_validation(journal, path):
    for name, index in journal.get('sourceValidation', []):
        try:
            if socket.if_nametoindex(name) == index:
                change_source_validation(index, 0)
        except OSError:
            if (Path('/sys/class/net') / name).exists():
                raise
    if journal.pop('sourceValidation', None):
        write_state(path, journal)


def collect_old(current=None):
    for entry in ROOT.glob('session-*.json'):
        if entry == current:
            continue
        old = json.loads(entry.read_text())
        revoke(old)
        restore_source_validation(old, entry)
        if not any(populated(item['path']) for item in old['scopes']):
            old['undo'] = undo(old)
            if old['undo']:
                write_state(entry, old)
            else:
                entry.unlink()


class Policy:
    def __init__(self, args):
        self.dns = [ipv4(ip) for ip in getattr(args, "dns", [])]
        if len(self.dns) > 4:
            raise RoutingError("Too many VPN DNS addresses")
        self.args = args
        self.links = verify_links(args)
        self.tun, self.uplink, self.tun_source, prefix = self.links
        self.subnet = str(ipaddress.ip_network(f'{args.source}/{prefix}', strict=False))
        token = secrets.token_hex(6)
        self.table = 'ogrs_' + token
        self.path = ROOT / ('session-' + token + '.json')
        base = 0x4e000000 | (secrets.randbits(22) << 1)
        self.marks = {'vpn': hex(base), 'direct': hex(base + 1)}
        self.state = {'table': self.table, 'scopes': [], 'undo': []}
        self.classifier = 'unprobed'
        self.ready = False

    def record(self, tool, remove):
        self.state['undo'].append([tool, remove])
        write_state(self.path, self.state)

    def add(self, tool, args, remove):
        run(tool, args)
        self.record(tool, remove)

    def routing_table(self, mode, interface, source):
        table = str(0x4e000000 + secrets.randbelow(0xffffff))
        all_routes = json.loads(run('ip', ['-j', '-4', 'route', 'show', 'table', 'all']))
        if any(str(route.get('table')) == table for route in all_routes):
            raise RoutingError('Session route table collision')
        existing = json.loads(run('ip', ['-j', '-4', 'rule', 'show']))
        mark = self.marks[mode]
        if any(str(rule.get('fwmark', '')).split('/')[0] == mark for rule in existing):
            raise RoutingError('Session routing mark collision')
        routes = []
        if mode == 'direct':
            routes.append([self.subnet, 'dev', interface, 'scope', 'link', 'src', source])
        route = ['default']
        if mode == 'direct' and self.args.gateway != '-':
            route.extend(['via', self.args.gateway, 'onlink'])
        routes.append([*route, 'dev', interface, 'src', source])
        for fields in routes:
            spec = ['table', table, *fields, 'proto', 'static']
            self.add('ip', ['-4', 'route', 'add', *spec], ['-4', 'route', 'del', *spec])
        # Local table priority 0 stays first; inspect the actual marked route before each grant.
        spec = ['priority', '80', 'fwmark', mark, 'lookup', table]
        self.add('ip', ['-4', 'rule', 'add', *spec], ['-4', 'rule', 'del', *spec])

    def install(self):
        a = self.args
        t = self.table
        vpn, direct = self.marks['vpn'], self.marks['direct']
        # Guard first. Even a leftover classifier with an expired lease cannot permit traffic.
        nft('\n'.join([
            f'create table inet {t}',
            f'add set inet {t} live {{ type mark; flags timeout; }}',
            f'add chain inet {t} scrub {{ type filter hook output priority -210; policy accept; }}',
            f'add rule inet {t} scrub meta mark {DIRECT_APPROVED} drop',
            f'add chain inet {t} select {{ type route hook output priority -145; policy accept; }}',
            # DNS to a VPN-assigned resolver always takes the VPN, including for direct apps.
            f'add chain inet {t} dns {{ type route hook output priority -140; policy accept; }}',
            *[f'add rule inet {t} dns meta mark {direct} ip daddr {address} {proto} dport 53 meta mark set {vpn}'
              for address in self.dns for proto in ('udp', 'tcp')],
            f'add chain inet {t} guard {{ type filter hook output priority -12; policy accept; }}',
            f'add rule inet {t} guard meta mark {QUARANTINE} drop',
            f'add rule inet {t} guard meta mark {{ {vpn}, {direct} }} oifname "lo" accept',
            f'add rule inet {t} guard meta mark {direct} udp dport {{ 53, 853 }} drop',
            f'add rule inet {t} guard meta mark {direct} tcp dport {{ 53, 853 }} drop',
            # LOCAL_OUT retains the initial output device in its hook state even
            # after policy routing recalculates the destination. POSTROUTING
            # observes the interface on which this packet will actually leave.
            f'add rule inet {t} guard meta mark {vpn} meta nfproto ipv4 meta mark @live ct mark set {vpn} accept',
            f'add rule inet {t} guard meta mark {direct} meta nfproto ipv4 meta mark @live ct mark set {direct} meta mark set {DIRECT_APPROVED} accept',
            f'add rule inet {t} guard meta mark {{ {vpn}, {direct} }} counter drop',
            # Let strict reverse-path validation consult the same route that
            # the outgoing connection used. Match only replies on its verified link.
            f'add chain inet {t} replies {{ type filter hook prerouting priority -149; policy accept; }}',
            f'add rule inet {t} replies meta iif {self.uplink} ct direction reply ct mark {direct} ct mark @live meta mark set {direct} accept',
            f'add rule inet {t} replies meta iif {self.tun} ct direction reply ct mark {vpn} ct mark @live meta mark set {vpn} accept',
            f'add rule inet {t} replies ct direction reply ct mark {{ {vpn}, {direct} }} counter drop',
            f'add chain inet {t} egress {{ type filter hook postrouting priority 98; policy accept; }}',
            # Browsers reach their PAC, CONNECT proxy and desktop DNS stub over loopback.
            f'add rule inet {t} egress oifname "lo" accept',
            f'add rule inet {t} egress meta mark {vpn} meta oif != {self.tun} counter drop',
            f'add rule inet {t} egress ct mark {direct} meta mark {DIRECT_APPROVED} meta oif != {self.uplink} counter drop',
            # First local route lookup can choose the other interface's source before OUTPUT rerouting.
            f'add chain inet {t} source {{ type nat hook postrouting priority 99; policy accept; }}',
            f'add rule inet {t} source meta mark {vpn} meta oif {self.tun} snat ip to {self.tun_source}',
            f'add rule inet {t} source ct mark {direct} meta mark {DIRECT_APPROVED} meta oif {self.uplink} snat ip to {a.source}',
        ]))
        self.record('nft', ['delete', 'table', 'inet', t])
        self.routing_table('vpn', a.tunnel, self.tun_source)
        self.routing_table('direct', a.uplink, a.source)
        config = Path('/proc/sys/net/ipv4/conf')
        for name, index in ((a.uplink, self.uplink), (a.tunnel, self.tun)):
            def effective(key):
                return max(int((config / link / key).read_text()) for link in ('all', name))
            if effective('rp_filter') == 1 and not effective('src_valid_mark'):
                self.state.setdefault('sourceValidation', []).append([name, index])
                write_state(self.path, self.state)
                change_source_validation(index, 1)
        self.probe_classifier()
        self.renew()

    def probe_classifier(self):
        path = next((line[3:].strip('/') for line in Path('/proc/self/cgroup').read_text().splitlines()
                     if line.startswith('0::')), '')
        if not path or not re.fullmatch(r'[a-zA-Z0-9@_.:/-]+', path):
            raise RoutingError('A cgroup v2 desktop session is required')
        try:
            nft(f'add chain inet {self.table} probe\nadd rule inet {self.table} probe socket cgroupv2 level 1 "{path.split("/")[0]}" counter\ndelete chain inet {self.table} probe')
            self.classifier = 'nft_cgroupv2'
        except RoutingError:
            for tool in ('iptables', 'ip6tables'):
                run(tool, ['-w', '2', '-t', 'mangle', '-N', self.table])
                try:
                    run(tool, ['-w', '2', '-t', 'mangle', '-A', self.table, '-m', 'cgroup', '--path', path, '-j', 'RETURN'])
                finally:
                    run(tool, ['-w', '2', '-t', 'mangle', '-F', self.table])
                    run(tool, ['-w', '2', '-t', 'mangle', '-X', self.table])
            self.classifier = 'xt_cgroup'

    def renew(self):
        if self.links != verify_links(self.args):
            raise RoutingError('The active network generation changed')
        unmarked, = json.loads(run('ip', ['-j', '-4', 'route', 'get', '192.0.2.127']))
        if unmarked.get('dev') != self.args.tunnel:
            raise RoutingError('The VPN no longer owns the default connection')
        for mode, interface in [('vpn', self.args.tunnel), ('direct', self.args.uplink)]:
            route, = json.loads(run('ip', ['-j', '-4', 'route', 'get', '192.0.2.127',
                                            'mark', self.marks[mode]]))
            if route.get('dev') != interface:
                raise RoutingError('Policy routing no longer selects the verified link')
        marks = ', '.join(m + f' timeout {LEASE_SECONDS}s' for m in self.marks.values())
        nft(f'flush set inet {self.table} live\nadd element inet {self.table} live {{ {marks} }}')
        self.ready = True

    def admit(self, scope, mode):
        if len(self.state['scopes']) >= MAX_SCOPES:
            self.collect_exited()
        if len(self.state['scopes']) >= MAX_SCOPES:
            raise RoutingError('Session launch capacity reached')
        if any(item['path'] == scope for item in self.state['scopes']):
            raise RoutingError('This process scope already has a policy')
        path = scope.lstrip('/')
        mark = self.marks[MODES[mode]]
        unit = path.rsplit('/', 1)[-1]
        # Match the socket creator and descendants, not the desktop user's UID.
        expression = f'socket cgroupv2 level {len(path.split("/"))} "{path}"'
        probe = f'add rule inet {self.table} select {expression} counter meta mark set {mark} comment "{unit}"'
        if self.classifier == 'nft_cgroupv2':
            nft(probe)
        elif self.classifier == 'xt_cgroup':
            # No executable starts until both families have a classifier. The inet guard drops IPv6.
            rule = ['OUTPUT', '-m', 'cgroup', '--path', path, '-j', 'MARK', '--set-mark', mark]
            for tool in ('ip6tables', 'iptables'):
                self.add(tool, ['-w', '2', '-t', 'mangle', '-I', *rule],
                         ['-w', '2', '-t', 'mangle', '-D', *rule])
        else:
            raise RoutingError('Scope classifier unavailable')
        self.state['scopes'].append({'path': scope, 'mode': mode})
        write_state(self.path, self.state)

    def revoke_scope(self, scope):
        entry = next((s for s in self.state['scopes'] if s['path'] == scope), None)
        if entry is None:
            raise RoutingError('This scope is not registered in the active session')
        if entry.get('revoked'):
            return entry['mode']
        if populated(scope):
            path = scope.lstrip('/')
            if self.classifier == 'nft_cgroupv2':
                # Insert before the original selector and terminate this base chain.
                expr = f'socket cgroupv2 level {len(path.split("/"))} "{path}"'
                unit = path.rsplit('/', 1)[-1]
                nft(f'insert rule inet {self.table} select {expr} drop comment "{unit}"')
            else:
                # Drop in mangle before any previous mark or route permission, including established flows.
                rule = ['OUTPUT', '-m', 'cgroup', '--path', path, '-j', 'DROP']
                for tool in ('ip6tables', 'iptables'):
                    self.add(tool, ['-w', '2', '-t', 'mangle', '-I', *rule],
                             ['-w', '2', '-t', 'mangle', '-D', *rule])
        entry['revoked'] = True
        write_state(self.path, self.state)
        return entry['mode']

    def collect_exited(self):
        # Match cgroup objects remain referenced by classifiers after app exit.
        # Remove only rules for unpopulated, recorded scopes in our own table.
        dead = [entry for entry in self.state['scopes'] if not populated(entry['path'])]
        if not dead:
            return
        paths = {entry['path'].lstrip('/') for entry in dead}
        if self.classifier == 'nft_cgroupv2':
            names = {path.rsplit('/', 1)[-1] for path in paths}
            rules = json.loads(run('nft', ['-j', '-a', 'list', 'chain', 'inet', self.table, 'select']))
            deletes = []
            for statement in rules['nftables']:
                rule = statement.get('rule', {})
                if rule.get('comment') in names:
                    deletes.append(f'delete rule inet {self.table} select handle {int(rule["handle"])}')
            if deletes:
                nft('\n'.join(deletes))
        else:
            retired = [item for item in self.state['undo'] if '--path' in item[1] and
                       item[1][item[1].index('--path') + 1] in paths]
            remaining = undo({'undo': retired})
            self.state['undo'] = [item for item in self.state['undo'] if item not in retired]
            self.state['undo'].extend(remaining)
        self.state['scopes'] = [entry for entry in self.state['scopes'] if entry not in dead]
        write_state(self.path, self.state)

    def status(self):
        scopes = [s for s in self.state['scopes'] if populated(s['path'])]
        return {'ok': True, 'version': 1, 'classifier': self.classifier,
                'tunnelIfindex': self.tun, 'activeScopes': scopes, 'ipv6': 'blocked'}

    def close(self):
        self.ready = False
        if self.path.exists():
            revoke(self.state)
            # A live process remains quarantined by its scope guard until exit.
            collect_old()


def root_directory():
    ROOT.mkdir(mode=0o755, exist_ok=True)
    info = ROOT.lstat()
    if info.st_uid != 0 or not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o022:
        raise RoutingError('Unsafe routing service directory')


def reply(peer, data):
    peer.send(json.dumps(data, separators=(',', ':')).encode())


def request(peer, policy, uid):
    pid, peer_uid, _ = struct.unpack('3i', peer.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
    if pid <= 0 or uid != peer_uid:
        raise RoutingError('The routing session belongs to another user')
    data, _, flags, _ = peer.recvmsg(256)
    if flags & socket.MSG_TRUNC:
        raise RoutingError('Oversized routing request')
    if data == b'status':
        return reply(peer, policy.status())
    if data == b'retire-websites':
        retired = []
        for scope in policy.state['scopes']:
            if scope['mode'].startswith('website-'):
                policy.revoke_scope(scope['path'])
                retired.append(scope['path'])
        return reply(peer, {'ok': True, 'closeScopes': retired})
    if data.startswith(b'revoke '):
        scope = data[7:].decode('ascii')
        mode = policy.revoke_scope(scope)
        return reply(peer, {'ok': True, 'closeScopes': [scope] if mode.startswith('website-') else []})
    mode = data.decode('ascii')
    if mode not in MODES:
        raise RoutingError('Unknown route selection')
    # Guard against exit/PID recycling while obtaining the scope from procfs.
    pidfd = os.pidfd_open(pid)
    try:
        scope = scope_of(pid, uid)
        if select.select([pidfd], [], [], 0)[0] or not populated(scope):
            raise RoutingError('The requesting scope has exited')
        policy.renew()
        policy.admit(scope, mode)
        reply(peer, {'ok': True, 'scope': scope, 'tunnelIfindex': policy.tun, 'dns': policy.dns})
    finally:
        os.close(pidfd)


def serve(args):
    if os.geteuid() != 0 or not 0 < args.uid < 0xffffffff:
        raise RoutingError('The active VPN service must start the routing session')
    args.source = ipv4(args.source)
    if args.gateway != '-':
        args.gateway = ipv4(args.gateway)
    root_directory()
    with (ROOT / 'owner.lock').open('a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as error:
            raise RoutingError('Another VPN session owns Linux routing') from error
        collect_old()
        policy = Policy(args)
        endpoint = ROOT / (str(args.uid) + '.sock')
        try:
            policy.install()
            with socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) as listener, selectors.DefaultSelector() as poll:
                with contextlib.suppress(FileNotFoundError):
                    endpoint.unlink()
                listener.bind(str(endpoint))
                os.chmod(endpoint, 0o600)
                os.chown(endpoint, args.uid, -1)
                listener.listen(8)
                poll.register(listener, selectors.EVENT_READ)
                poll.register(0, selectors.EVENT_READ)
                print('READY', flush=True)
                renewed = time.monotonic()
                while True:
                    events = poll.select(max(0, renewed + 1 - time.monotonic()))
                    if any(key.fd == 0 for key, _ in events):
                        # EOF or any owner command revokes the generation.
                        break
                    if time.monotonic() >= renewed + 1:
                        policy.collect_exited()
                        if policy.state['scopes']:
                            policy.renew()
                        renewed = time.monotonic()
                    for _, _event in events:
                        peer, _ = listener.accept()
                        with peer:
                            try:
                                peer.settimeout(0.3)
                                request(peer, policy, args.uid)
                            except (ValueError, OSError, RoutingError) as error:
                                with contextlib.suppress(OSError):
                                    reply(peer, {'ok': False, 'reason': str(error)})
        finally:
            policy.close()
            with contextlib.suppress(FileNotFoundError):
                endpoint.unlink()


def call(op):
    uid = os.getuid()
    with socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) as peer:
        peer.settimeout(6)
        peer.connect(str(ROOT / (str(uid) + '.sock')))
        _, server_uid, _ = struct.unpack('3i', peer.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
        if server_uid != 0:
            raise RoutingError('Expected the installed VPN routing service')
        peer.send(op.encode('ascii'))
        data, _, flags, _ = peer.recvmsg(65536)
        if flags & socket.MSG_TRUNC:
            raise RoutingError('Incomplete service reply')
        result = json.loads(data)
        if result.get('ok') is not True:
            raise RoutingError(result.get('reason', 'Routing admission failed'))
        return result


def close_website_scopes(scopes):
    # The owner has already withdrawn the network grant. Stop the desktop
    # user's full scope before the controller removes the temporary profile.
    # Chromium children can continue writing after the main process exits.
    pending = [scope for scope in scopes if populated(scope)]
    if not pending:
        return
    units = [scope.rsplit('/', 1)[-1] for scope in pending]
    if not all(UNIT.fullmatch(unit) for unit in units):
        raise RoutingError('Unexpected browser scope name')
    for command in (['stop', '--no-block'], ['kill', '--signal=SIGKILL']):
        try:
            subprocess.run(['/usr/bin/systemctl', '--user', *command, *units],
                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2)
        except subprocess.TimeoutExpired:
            pass
        deadline = time.monotonic() + 2
        while any(populated(scope) for scope in pending):
            if time.monotonic() >= deadline:
                break
            time.sleep(0.05)
        else:
            return
    raise RoutingError('The browser session is still closing')


def revoke_from_desktop(scope):
    try:
        receipt = call('revoke ' + scope)
    except (OSError, ValueError, RoutingError):
        # Disconnect can retire the network owner while this window is open.
        # Its own user manager can still stop the disposable website scope.
        if (managed_scope(scope, os.getuid()) and
                scope.rsplit('/', 1)[-1].startswith(WEBSITE_UNIT_PREFIX)):
            close_website_scopes([scope])
        raise
    close_website_scopes(receipt.get('closeScopes', []))
    return receipt


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest='command', required=True)
    worker = sub.add_parser('serve')
    for field in ('uid', 'tunnel', 'uplink', 'gateway', 'source'):
        worker.add_argument('--' + field, required=True, type=int if field == 'uid' else str)
    worker.add_argument('--dns', action='append', default=[])
    for op in ('launch', 'claim'):
        launch = sub.add_parser(op)
        launch.add_argument('mode', choices=MODES)
        launch.add_argument('argv', nargs=argparse.REMAINDER)
    sub.add_parser('revoke').add_argument('scope')
    sub.add_parser('status')
    sub.add_parser('retire-websites')
    args = parser.parse_args()
    if args.command == 'serve':
        def stop(_num, _frame):
            raise SystemExit(0)
        signal.signal(signal.SIGTERM, stop)
        serve(args)
    elif args.command == 'revoke':
        print(json.dumps(revoke_from_desktop(args.scope)))
    elif args.command == 'retire-websites':
        try:
            receipt = call('retire-websites')
        except FileNotFoundError:
            pass  # No active VPN owner. Website lists remain editable offline.
        except ConnectionRefusedError:
            time.sleep(LEASE_SECONDS + 1)  # Let a crashed owner's last lease expire.
        else:
            close_website_scopes(receipt.get('closeScopes', []))
    elif args.command == 'status':
        print(json.dumps(call('status')))
    else:
        argv = args.argv[1:] if args.argv and args.argv[0] == '--' else args.argv
        if os.getuid() == 0 or not argv or not os.path.isabs(argv[0]):
            raise RoutingError('Launch requires a normal user and an absolute executable')
        if args.command == 'launch':
            prefix = WEBSITE_UNIT_PREFIX if args.mode.startswith('website-') else 'app-obfusgatedroute-'
            unit = prefix + secrets.token_hex(16) + '.scope'
            runner = '/usr/bin/systemd-run'
            os.execv(runner, [runner, '--quiet', '--user', '--scope', '--unit=' + unit, '--',
                              str(Path(__file__).resolve()), 'claim', args.mode, '--', *argv])
        receipt = call(args.mode)
        if receipt['scope'] != scope_of(os.getpid(), os.getuid()):
            raise RoutingError('The launcher moved to another process scope')
        os.environ['OBFUSGATED_ROUTING_SCOPE'] = receipt['scope']
        os.environ['OBFUSGATED_ROUTING_VPN_IFINDEX'] = str(receipt['tunnelIfindex'])
        os.environ['OBFUSGATED_ROUTING_DNS'] = ','.join(receipt['dns'])
        os.execv(argv[0], argv)


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, KeyError, RoutingError) as error:
        print('Traffic routing:', error, file=sys.stderr)
        sys.exit(1)
