#!/usr/bin/env python3
# summary: Offer or receive remote help through a private invitation.
"""starchaser help start offer | start connect CODE | status | stop

One-way help over an invitation-authenticated, encrypted internet connection. No shared VPN account is needed.
An invitation lasts ten minutes; an allowed session lasts at most two hours and needs the visible End help bar.
"""
import contextlib
import hashlib
import importlib.machinery
import importlib.util
import json
import os
import re
import secrets
import subprocess
import sys
import time
from pathlib import Path

RUNTIME = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}')
STATUS = RUNTIME / 'starchaser-help.json'
APP_ID = 'org.starchaser.help/v1'


def wormhole_code(code):
    digits = str(code).replace(' ', '')
    if not re.fullmatch(r'[1-9][0-9]{8}', digits):
        raise ValueError('Type the nine-digit code shown on their computer.')
    return digits[:3] + '-' + digits[3:]


def invitation_pending(started, now=None):
    return 0 <= (time.monotonic() if now is None else now) - started < 600


def extend_consent_deadline(opened, deadline, now=None):
    stamp = time.monotonic() if now is None else now
    return min(opened + 1800, max(deadline, stamp) + 120)


def comparison_code(verifier):
    return f'{int.from_bytes(hashlib.sha256(verifier + b"starchaser help").digest()[:4], "big") % 1000000:06d}'


def forward_destination(service):
    if service != 'ssh':
        raise ValueError('Help only forwards the authenticated remote sign-in connection.')
    return '127.0.0.1', 22


def link_module():
    loader = importlib.machinery.SourceFileLoader('starchaser_help_link', str(Path(__file__).resolve().with_name('starchaser-link')))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    module = importlib.util.module_from_spec(spec)
    loader.exec_module(module)
    return module


def ensure_producer_controls(protocol_type):
    """Magic Wormhole 0.24's connection omits producer methods used by its own inbound flow control.
    Delegate to the underlying TCP transport, preserving any implementation supplied by a newer release."""
    def delegate(method):
        def forwarded(self):
            return getattr(self.transport, method)()
        return forwarded
    for method in ('pauseProducing', 'resumeProducing', 'stopProducing'):
        if not hasattr(protocol_type, method):
            setattr(protocol_type, method, delegate(method))


def run_session(mode, digits):
    # Import optional transport dependencies only when making an invitation, so status and Stop always work.
    import wormhole
    from wormhole.cli import public_relay
    from wormhole._dilation.connection import DilatedConnectionProtocol
    ensure_producer_controls(DilatedConnectionProtocol)
    from twisted.internet import defer, task, threads
    from twisted.internet.endpoints import TCP4ServerEndpoint
    from twisted.internet.protocol import Factory, Protocol
    from twisted.protocols.portforward import Proxy, ProxyClientFactory, ProxyFactory
    L = link_module()
    target = mode == 'offer'
    granted = False
    entry = None
    invitation = digits or str(100000000 + secrets.randbelow(900000000))
    code = wormhole_code(invitation)
    L.jwrite(STATUS, {'state': 'waiting', 'code': invitation if target else '', 'mode': mode, 'started': time.time()})

    async def session(reactor):
        nonlocal granted, entry
        w = wormhole.create(APP_ID, public_relay.MAILBOX_RELAY, reactor, dilation=True, versions={'help': 1})
        w.set_code(code)
        listener = None
        request = answer = None
        timer = reactor.callLater(600, lambda: w.close())
        async def teardown():
            if listener:
                await defer.maybeDeferred(listener.stopListening)
            with contextlib.suppress(Exception):
                await w.close()
        try:
            verifier = await w.get_verifier()
            versions = await w.get_versions()
            if versions.get('help') != 1:
                raise ValueError('The other computer needs a current Starchaser update.')
            L.fleet().ensure_personal_key()
            hello = L.hello()
            w.send_message(json.dumps({'hello': hello, 'mode': mode}).encode())
            raw = await w.get_message()
            if len(raw) > 16384:
                raise ValueError('The help request is too large.')
            message = json.loads(raw)
            peer = message.get('hello')
            if message.get('mode') != ('connect' if target else 'offer') or not L.valid_hello(peer):
                raise ValueError("That isn't a valid Starchaser help request.")
            member = L.fleet().find(L.fleet().load(), "dev-" + peer['id'])
            if member:
                error = (f"{L.safe_name(peer.get('name'))} is already in your fleet, so it can manage this computer from Mission Control. Help codes are for computers outside your fleet."
                         if target else f"{L.safe_name(peer.get('name'))} is already in your fleet. Open it in Mission Control.")
                L.jwrite(STATUS, {'state': 'error', 'mode': mode, 'error': error, 'computer': member['id'], 'name': L.safe_name(peer.get('name'))})
                raise ValueError(error)
            if timer.active():
                timer.cancel()
            # Both peers have authenticated the single-use invitation. Allow and More time now
            # use the target's consent clock, even if authentication took almost ten minutes.
            # Bound the helper's wait too, with 30 seconds for delivery after the target's
            # maximum 30-minute question. No forwarding or keys are granted before Allow.
            timer = reactor.callLater(1830, lambda: w.close())
            compare = comparison_code(verifier)
            name = L.safe_name(peer.get('name'))
            L.jwrite(STATUS, {'state': 'confirm', 'mode': mode, 'name': name, 'comparison': compare,
                             'code': invitation if target else '', 'started': time.time()})
            if target:
                rid = secrets.token_hex(4)
                request, answer = L.PENDING / (rid + '.json'), L.PENDING / (rid + '.answer')
                L.jwrite(request, {'id': rid, 'from': {k: peer.get(k) for k in ('id', 'name', 'user', 'kind')},
                                  'address': 'Help from anywhere', 'code': compare, 'time': int(time.time()), 'help': True})
                pending_started = time.monotonic()
                consent_deadline = pending_started + 120
                more = L.PENDING / (rid + '.more')
                while not answer.exists():
                    if more.exists():
                        more.unlink(missing_ok=True)
                        consent_deadline = extend_consent_deadline(pending_started, consent_deadline)
                    if time.monotonic() >= consent_deadline:
                        raise ValueError('The invitation ended. Ask for help again.')
                    await task.deferLater(reactor, 0.2, lambda: None)
                if answer.read_text().strip() != 'yes':
                    raise ValueError('Help was declined. Nothing was let in.')
                # Complete target authorization before announcing acceptance or opening the SSH forward.
                await threads.deferToThread(L.trust_help, dict(peer, role='helper'), '127.0.0.1')
                granted = True
                w.send_message(b'{"allowed":true}')
            else:
                allowed = await w.get_message()
                if allowed != b'{"allowed":true}':
                    raise ValueError("The other computer didn't allow help.")
            if timer.active():
                timer.cancel()
            endpoints = w.dilate(transit_relay_location=public_relay.TRANSIT_RELAY, no_listen=True)
            if target:
                destination = forward_destination('ssh')
                listener = await endpoints.listener_for('ssh').listen(ProxyFactory(*destination))
            else:
                endpoint = endpoints.connector_for('ssh')
                class LocalProxy(Proxy):
                    def connectionMade(self):
                        self.transport.pauseProducing()
                        client = ProxyClientFactory()
                        client.setServer(self)
                        endpoint.connect(client).addErrback(lambda failure: self.transport.loseConnection())
                factory = Factory(); factory.protocol = LocalProxy
                listener = await TCP4ServerEndpoint(reactor, 0, interface='127.0.0.1').listen(factory)
                port = listener.getHost().port
                entry = await threads.deferToThread(L.trust_help, dict(peer, role='help-target', relayPort=port), '127.0.0.1')
            L.jwrite(STATUS, {'state': 'connected', 'mode': mode, 'name': name,
                             'computer': entry['id'] if entry else '', 'started': time.time()})
            # Heartbeats use a Noise-encrypted subchannel, never the store-and-forward mailbox.
            alive = [time.monotonic()]
            class Alive(Protocol):
                def dataReceived(self, data):
                    if data != b".":
                        self.transport.loseConnection(); return
                    alive[0] = time.monotonic()
                    if target:
                        self.transport.write(b".")
            alive_factory = Factory(); alive_factory.protocol = Alive
            pulse = None
            if target:
                await endpoints.listener_for('alive').listen(alive_factory)
                w.send_message(b'{"ready":true}')
            else:
                if await w.get_message() != b'{"ready":true}':
                    raise ValueError("The help connection couldn't start.")
                pulse = await endpoints.connector_for('alive').connect(alive_factory)
            started = time.monotonic()
            while time.monotonic() - started < L.HELP_SECONDS:
                if target and not L.help_status()['active']:
                    break
                if time.monotonic() - alive[0] > 15:
                    break
                if pulse:
                    pulse.transport.write(b".")
                await task.deferLater(reactor, 5, lambda: None)
        except Exception as error:
            if L.jread(STATUS, {}).get('state') != 'error':
                L.jwrite(STATUS, {'state': 'error', 'mode': mode, 'error': str(error) if isinstance(error, ValueError) else "Help couldn't connect. Ask for a new code and try again."})
            raise
        finally:
            if timer.active():
                timer.cancel()
            if request:
                request.unlink(missing_ok=True)
            if answer:
                answer.unlink(missing_ok=True)
            if request:
                request.with_suffix('.more').unlink(missing_ok=True)
            await teardown()
    try:
        task.react(lambda reactor: defer.ensureDeferred(session(reactor)))
    finally:
        if target and granted:
            L.end_help()
        if entry:
            with contextlib.suppress(Exception):
                L.fleet().remove_flow(entry['id'])
            with contextlib.suppress(Exception):
                for paired in L.load_peers():
                    if paired.get('role') == 'help-target' and paired.get('helpEntry') == entry['id']:
                        L.forget(paired['id'])
        last = L.jread(STATUS, {})
        if last.get('state') != 'error':
            L.jwrite(STATUS, {'state': 'ended', 'mode': mode, 'connected': last.get('state') == 'connected'})


def main(argv):
    if not argv or argv[0] in ('-h', '--help', 'help'):
        print(__doc__); return 0
    if argv == ['status']:
        try:
            value = json.loads(STATUS.read_text())
        except (OSError, ValueError):
            value = {'state': 'off'}
        print(json.dumps(value)); return 0
    if argv == ['stop']:
        subprocess.run(['systemctl', '--user', 'stop', 'starchaser-help-session.service'], capture_output=True)
        link_module().end_help()
        return 0
    if argv[:1] == ['start'] and len(argv) in (2, 3) and argv[1] in ('offer', 'connect'):
        if argv[1] == 'connect':
            if len(argv) != 3:
                raise ValueError('Type their nine-digit help code.')
            wormhole_code(argv[2])
        import importlib.util
        if not importlib.util.find_spec('wormhole') or not importlib.util.find_spec('noise'):
            raise ValueError('Help from anywhere needs an update. Open Settings › Updates, then try again.')
        command = [sys.executable, str(Path(__file__).resolve()), '_run', *argv[1:]]
        result = subprocess.run(['systemd-run', '--user', '--collect', '--quiet', '--unit=starchaser-help-session',
                                 '--property=RuntimeMaxSec=2h', '--', *command], capture_output=True, text=True)
        if result.returncode:
            raise ValueError("A help session is already running, or it couldn't start. Choose End help and try again.")
        print('{"ok":true}'); return 0
    if argv[:1] == ['_run'] and len(argv) in (2, 3) and argv[1] in ('offer', 'connect'):
        run_session(argv[1], argv[2] if len(argv) == 3 else '')
        return 0
    raise ValueError('Use start offer, start connect CODE, status or stop.')


if __name__ == '__main__':
    try:
        raise SystemExit(main(sys.argv[1:]))
    except (ValueError, ImportError, OSError) as error:
        print(json.dumps({'ok': False, 'error': str(error)})); raise SystemExit(1)
