#!/usr/bin/python3
"""wol-relayd - Wake-on-LAN relay daemon for KEA DHCP hosts.

A small HTTP daemon deployed on the KEA DHCP servers (which have layer
2 access to their subnets).  It receives wake requests over HTTP and
emits the magic packets on the according (directed) broadcast address:

- ``GET /health``: version and the broadcast addresses it may serve.
- ``GET /state``: the neighbor state (ARP/NDP table) of the host, used
  by the trytond ``cmdb_ipam`` module to record when a MAC address was
  last seen awake.
- ``POST /wake`` ``{"mac": "...", "broadcast": "..."}``: send the magic
  packet to the broadcast address (must be one of the configured
  networks).

Configuration pull
------------------

The allowed broadcast addresses (``networks``) and the KEA
configuration fragment do not need to be static in the configuration
file.  When a tryton server is configured (``server_url``,
``server_database``, ``server_token`` and ``wol_server``), the daemon
actively pulls its configuration from the
``GET /<database>/cmdb_ipam/wol/config`` endpoint of the trytond
``cmdb_ipam`` module and applies every revision change:

- the dynamic list of broadcast addresses of the subnets assigned to
  the ``cmdb.ipam.wol.server`` replaces the static ``networks``,
- the revision and the networks are persisted in a state file so a
  restart keeps working even when the tryton server is unreachable,
- the KEA configuration fragment is written to ``config_file``
  (atomic replace), validated with ``validate_command`` (the file is
  kept unchanged on validation failure) and activated with
  ``reload_command``.

Delivery is near-realtime: the pull is a revision based long poll
answered by the server within a second of a relevant change.

Authentication: a static bearer token (``auth_token`` in the config)
for the daemon API and the ``server_token`` for the tryton server.
The daemon needs no raw sockets and can run unprivileged.
"""
import argparse
import configparser
import ipaddress
import json
import logging
import os
import shlex
import socket
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

__version__ = '1.1'

DEFAULT_PORT = 9696
DEFAULT_WAKE_PORT = 9
DEFAULT_WAKE_REPEAT = 3
DEFAULT_WAKE_DELAY = 0.05
DEFAULT_CONFIG_SYNC_INTERVAL = 3600
DEFAULT_CONFIG_SYNC_WAIT = 25
CONFIG_RETRY_DELAY = 30
DEFAULT_STATE_FILE = '/var/lib/wol-relayd/config.json'

logger = logging.getLogger('wol-relayd')


class ConfigSyncError(Exception):
    "Error while pulling or applying the configuration from tryton."


def normalize_mac(value):
    "Return the MAC address as 'aa:bb:cc:dd:ee:ff' or None."
    if not value:
        return None
    mac = value.strip().lower().replace('-', ':')
    parts = mac.split(':')
    if len(parts) != 6:
        return None
    try:
        return ':'.join('%02x' % int(part, 16) for part in parts)
    except ValueError:
        return None


def build_magic_packet(mac):
    "Return the magic packet bytes for the MAC address."
    return b'\xff' * 6 + bytes.fromhex(mac.replace(':', '')) * 16


def send_magic_packet(mac, broadcast, port=DEFAULT_WAKE_PORT,
        repeat=DEFAULT_WAKE_REPEAT, delay=DEFAULT_WAKE_DELAY):
    "Send the magic packet to the broadcast address via UDP."
    packet = build_magic_packet(mac)
    sent = 0
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        for index in range(repeat):
            sock.sendto(packet, (broadcast, port))
            sent += 1
            if index + 1 < repeat and delay:
                time.sleep(delay)
    return sent


def read_ip_neigh():
    "Return the neighbor entries of 'ip neigh show'."
    try:
        output = subprocess.run(
            ['ip', 'neigh', 'show'], capture_output=True, text=True,
            timeout=10, check=True).stdout
    except (OSError, subprocess.SubprocessError):
        return read_proc_net_arp()
    return parse_ip_neigh(output)


def parse_ip_neigh(output):
    "Parse the output of 'ip neigh show' into neighbor entries."
    neighbors = []
    for line in output.splitlines():
        fields = line.split()
        if len(fields) < 5 or fields[1] != 'dev' or 'lladdr' not in fields:
            continue
        address, _, device = fields[:3]
        state = fields[-1]
        lladdr = fields[fields.index('lladdr') + 1]
        mac = normalize_mac(lladdr)
        if mac is None:
            continue
        neighbors.append({
            'ip': address,
            'dev': device,
            'state': state,
            'mac': mac,
            })
    return neighbors


def read_proc_net_arp():
    "Return the neighbor entries of /proc/net/arp."
    neighbors = []
    try:
        with open('/proc/net/arp', encoding='ascii') as arp_file:
            next(arp_file)
            for line in arp_file:
                fields = line.split()
                if len(fields) < 6:
                    continue
                mac = normalize_mac(fields[3])
                if mac is None:
                    continue
                neighbors.append({
                    'ip': fields[0],
                    'dev': fields[5],
                    'state': fields[2],
                    'mac': mac,
                    })
    except OSError as exc:
        logger.warning('cannot read /proc/net/arp: %s', exc)
    return neighbors


def fetch_server_config(url, database_name, token, server_name,
        revision=None, wait=0, verify_ssl=True, timeout=None):
    """Pull the configuration document from the tryton server.

    Return the validated document or raise a ``ConfigSyncError``.
    """
    if url.endswith('/'):
        url = url[:-1]
    params = {'server': server_name}
    if revision:
        params['revision'] = revision
    if wait:
        params['wait'] = '%g' % wait
    request_url = '%s/%s/cmdb_ipam/wol/config?%s' % (
        url, urllib.parse.quote(database_name, safe=''),
        urllib.parse.urlencode(params))
    handlers = []
    if not verify_ssl:
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        handlers.append(urllib.request.HTTPSHandler(context=context))
    opener = urllib.request.build_opener(*handlers)
    request = urllib.request.Request(request_url, headers={
            'Authorization': 'Bearer %s' % token,
            'Accept': 'application/json',
            })
    try:
        response = opener.open(request, timeout=timeout)
        body = response.read()
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode('utf-8', 'replace').strip()
        raise ConfigSyncError(
            'server error %s: %s' % (exc.code, detail or str(exc))
            ) from exc
    except OSError as exc:
        raise ConfigSyncError('cannot reach server: %s' % exc) from exc
    try:
        document = json.loads(body.decode('utf-8'))
    except (ValueError, UnicodeDecodeError) as exc:
        raise ConfigSyncError('invalid JSON response') from exc
    return validate_config_document(document)


def validate_config_document(document):
    "Validate a configuration document and return it."
    if not isinstance(document, dict):
        raise ConfigSyncError('invalid configuration document')
    changed = document.get('changed')
    revision = document.get('revision')
    if not isinstance(changed, bool) or not isinstance(revision, str):
        raise ConfigSyncError('invalid configuration document')
    if not changed:
        return document
    broadcasts = document.get('broadcasts')
    if not isinstance(broadcasts, list) or not all(
            isinstance(broadcast, str) for broadcast in broadcasts):
        raise ConfigSyncError('invalid broadcasts list')
    for broadcast in broadcasts:
        try:
            ipaddress.ip_address(broadcast)
        except ValueError:
            raise ConfigSyncError(
                'invalid broadcast address %r' % broadcast) from None
    kea = document.get('kea')
    if not isinstance(kea, dict) or not isinstance(
            kea.get('subnets4'), list) or not isinstance(
            kea.get('subnets6'), list):
        raise ConfigSyncError('invalid kea configuration')
    return document


def _run_kea_command(command, path):
    """Run a command with the path substituted for %s.

    Raise a ``ConfigSyncError`` when the command fails.
    """
    if '%s' in command:
        command = command.replace('%s', shlex.quote(path))
    try:
        completed = subprocess.run(
            shlex.split(command), capture_output=True, text=True,
            timeout=120)
    except (OSError, subprocess.SubprocessError) as exc:
        raise ConfigSyncError(
            'cannot run %r: %s' % (command, exc)) from exc
    output = (completed.stdout + completed.stderr).strip()
    if completed.returncode != 0:
        raise ConfigSyncError(
            'command %r failed with status %d: %s' % (
                command, completed.returncode, output or '(no output)'))
    return output


def apply_kea_config(config, kea_payload):
    """Write the KEA configuration fragment and activate it.

    The fragment is written atomically to ``config.kea_config_file``
    after passing ``config.kea_validate_command``, so the previous
    configuration is never replaced by an invalid one.  The new
    configuration is activated with ``config.kea_reload_command``.
    """
    path = config.kea_config_file
    content = json.dumps(kea_payload, indent=4, sort_keys=True) + '\n'
    directory = os.path.dirname(path) or '.'
    try:
        os.makedirs(directory, exist_ok=True)
    except OSError as exc:
        raise ConfigSyncError(
            'cannot create directory %s: %s' % (directory, exc)) from exc
    descriptor, tmp_path = tempfile.mkstemp(
        dir=directory, prefix='.%s.' % os.path.basename(path),
        suffix='.tmp')
    try:
        with os.fdopen(descriptor, 'w', encoding='utf-8') as tmp_file:
            tmp_file.write(content)
        if config.kea_validate_command:
            _run_kea_command(config.kea_validate_command, tmp_path)
        os.replace(tmp_path, path)
    except Exception:
        try:
            os.unlink(tmp_path)
        except OSError:
            pass
        raise
    logger.info('wrote KEA configuration to %s', path)
    if config.kea_reload_command:
        _run_kea_command(config.kea_reload_command, path)
        logger.info('reloaded KEA via %r', config.kea_reload_command)


class RelayConfig:
    "The configuration of the relay daemon."

    def __init__(self, listen_host='0.0.0.0', listen_port=DEFAULT_PORT,
            auth_token=None, networks=(), wake_port=DEFAULT_WAKE_PORT,
            wake_repeat=DEFAULT_WAKE_REPEAT, wake_delay=DEFAULT_WAKE_DELAY,
            server_url=None, server_database=None, server_token=None,
            wol_server=None,
            config_sync_interval=DEFAULT_CONFIG_SYNC_INTERVAL,
            config_sync_wait=DEFAULT_CONFIG_SYNC_WAIT,
            server_verify_ssl=True, state_file=None, kea_config_file=None,
            kea_validate_command=None, kea_reload_command=None):
        self.listen_host = listen_host
        self.listen_port = listen_port
        self.auth_token = auth_token
        self.networks = list(networks)
        self.wake_port = wake_port
        self.wake_repeat = wake_repeat
        self.wake_delay = wake_delay
        self.server_url = server_url
        self.server_database = server_database
        self.server_token = server_token
        self.wol_server = wol_server
        self.config_sync_interval = config_sync_interval
        self.config_sync_wait = config_sync_wait
        self.server_verify_ssl = server_verify_ssl
        self.state_file = state_file
        self.kea_config_file = kea_config_file
        self.kea_validate_command = kea_validate_command
        self.kea_reload_command = kea_reload_command

    @classmethod
    def load(cls, path):
        "Load the configuration from an INI file."
        # Commands may contain the %s placeholder, so no interpolation.
        parser = configparser.ConfigParser(interpolation=None)
        read = parser.read(path)
        if not read:
            raise SystemExit('cannot read config file %s' % path)
        section = parser['wol-relayd'] if parser.has_section(
            'wol-relayd') else {}
        networks = [
            network.strip()
            for network in section.get('networks', '').split(',')
            if network.strip()]
        for network in networks:
            try:
                ipaddress.ip_address(network)
            except ValueError:
                raise SystemExit(
                    'invalid broadcast address %r in config' % network)
        kea_section = (
            parser['kea'] if parser.has_section('kea') else {})
        return cls(
            listen_host=section.get('listen_host', '0.0.0.0'),
            listen_port=section.getint('listen_port', DEFAULT_PORT),
            auth_token=section.get('auth_token') or None,
            networks=networks,
            wake_port=section.getint('wake_port', DEFAULT_WAKE_PORT),
            wake_repeat=section.getint(
                'wake_repeat', DEFAULT_WAKE_REPEAT),
            wake_delay=section.getfloat(
                'wake_delay', DEFAULT_WAKE_DELAY),
            server_url=section.get('server_url') or None,
            server_database=section.get('server_database') or None,
            server_token=section.get('server_token') or None,
            wol_server=section.get('wol_server') or None,
            config_sync_interval=section.getint(
                'config_sync_interval', DEFAULT_CONFIG_SYNC_INTERVAL),
            config_sync_wait=section.getint(
                'config_sync_wait', DEFAULT_CONFIG_SYNC_WAIT),
            server_verify_ssl=section.getboolean(
                'server_verify_ssl', True),
            state_file=section.get('state_file') or None,
            kea_config_file=kea_section.get('config_file') or None,
            kea_validate_command=(
                kea_section.get('validate_command') or None),
            kea_reload_command=(
                kea_section.get('reload_command') or None),
            )

    def get_state_file(self):
        "Return the path of the configuration state file or None."
        if self.state_file:
            return self.state_file
        if self.config_sync_enabled:
            return DEFAULT_STATE_FILE
        return None

    @property
    def config_sync_enabled(self):
        "Whether the configuration is pulled from the tryton server."
        return bool(
            self.server_url and self.server_database
            and self.server_token and self.wol_server)

    def check_broadcast(self, broadcast):
        "Whether the broadcast address may be used."
        if not self.networks:
            return True
        return broadcast in self.networks


class RelayState:
    "Shared state of the relay daemon."

    def __init__(self, config):
        self.config = config
        self.started = time.time()
        self._lock = threading.Lock()
        self._dynamic_networks = None
        self.networks_revision = None
        self.last_config_sync = None
        self.config_error = None
        self._load_state()

    def _load_state(self):
        "Restore the applied configuration from the state file."
        path = self.config.get_state_file()
        if path is None:
            return
        try:
            with open(path, encoding='utf-8') as state_file:
                state = json.load(state_file)
        except (OSError, ValueError) as exc:
            logger.warning('cannot read state file %s: %s', path, exc)
            return
        try:
            revision = state['revision']
            networks = state['networks']
        except (TypeError, KeyError):
            logger.warning('invalid state file %s', path)
            return
        if not isinstance(revision, str) or not isinstance(networks, list):
            logger.warning('invalid state file %s', path)
            return
        with self._lock:
            self._dynamic_networks = list(networks)
            self.networks_revision = revision
        logger.info('restored configuration revision %s from %s',
            revision[:12], path)

    def _save_state(self):
        "Persist the applied revision and networks to the state file."
        path = self.config.get_state_file()
        if path is None:
            return
        with self._lock:
            state = {
                'revision': self.networks_revision,
                'networks': list(self._dynamic_networks or ()),
                'saved': time.time(),
                }
        directory = os.path.dirname(path) or '.'
        try:
            os.makedirs(directory, exist_ok=True)
            descriptor, tmp_path = tempfile.mkstemp(
                dir=directory, prefix='.%s.' % os.path.basename(path),
                suffix='.tmp')
            with os.fdopen(descriptor, 'w', encoding='utf-8') as tmp_file:
                json.dump(state, tmp_file)
            os.replace(tmp_path, path)
        except OSError as exc:
            logger.warning(
                'cannot persist configuration state to %s: %s', path, exc)

    def apply_config(self, revision, document):
        "Apply a configuration document from the tryton server."
        document = validate_config_document(document)
        broadcasts = document['broadcasts']
        with self._lock:
            previous_revision = self.networks_revision
            self._dynamic_networks = list(broadcasts)
            self.networks_revision = revision
        self._save_state()
        try:
            if self.config.kea_config_file:
                apply_kea_config(self.config, document['kea'])
        except ConfigSyncError:
            with self._lock:
                self.networks_revision = previous_revision
            raise
        logger.info(
            'applied configuration revision %s (%d networks)',
            revision[:12], len(broadcasts))

    def health(self):
        "Return the health information."
        with self._lock:
            networks = self._dynamic_networks
        data = {
            'version': __version__,
            'uptime': int(time.time() - self.started),
            'broadcasts': list(
                networks if networks is not None
                else self.config.networks),
            }
        if self.config.config_sync_enabled:
            data.update({
                'config_sync': True,
                'revision': self.networks_revision,
                'last_config_sync': self.last_config_sync,
                'config_error': self.config_error,
                })
        return data

    def check_broadcast(self, broadcast):
        "Whether the broadcast address may be used."
        with self._lock:
            networks = self._dynamic_networks
        if networks is not None:
            return broadcast in networks
        return self.config.check_broadcast(broadcast)

    def wake(self, mac, broadcast):
        "Send the magic packet and return the number of packets sent."
        if not self.check_broadcast(broadcast):
            raise ValueError('broadcast %s is not allowed' % broadcast)
        return send_magic_packet(
            mac, broadcast,
            port=self.config.wake_port,
            repeat=self.config.wake_repeat,
            delay=self.config.wake_delay)


class ConfigSync(threading.Thread):
    """Background thread pulling the configuration from the tryton server.

    Each request is a revision based long poll: the server answers as
    soon as the configuration revision differs from the applied one.
    Every ``config_sync_interval`` seconds a full refresh is forced by
    omitting the revision parameter.
    """

    def __init__(self, config, state):
        super().__init__(name='config-sync', daemon=True)
        self.config = config
        self.state = state
        self.stopped = threading.Event()

    def run(self):
        logger.info(
            'config sync active (server=%s, interval=%ss, wait=%ss)',
            self.config.server_url, self.config.config_sync_interval,
            self.config.config_sync_wait)
        next_full_refresh = time.time()
        while not self.stopped.is_set():
            started = time.time()
            full_refresh = started >= next_full_refresh
            if full_refresh:
                next_full_refresh = (
                    started + self.config.config_sync_interval)
            try:
                applied = self.sync_once(full_refresh=full_refresh)
            except ConfigSyncError as exc:
                self.state.config_error = str(exc)
                logger.warning('config sync failed: %s', exc)
                self.stopped.wait(CONFIG_RETRY_DELAY)
                continue
            self.state.config_error = None
            self.state.last_config_sync = time.time()
            # Ensure a minimum cycle time so a server without long poll
            # support does not cause a busy loop.  After an applied
            # change the next pull starts immediately.
            remaining = self.config.config_sync_wait - (
                time.time() - started)
            if remaining > 0 and not applied:
                self.stopped.wait(remaining)

    def sync_once(self, full_refresh=False):
        "Perform one configuration pull and apply it when changed."
        response = fetch_server_config(
            self.config.server_url, self.config.server_database,
            self.config.server_token, self.config.wol_server,
            revision=None if full_refresh else self.state.networks_revision,
            wait=self.config.config_sync_wait,
            verify_ssl=self.config.server_verify_ssl)
        self.state.last_config_sync = time.time()
        if (response['changed']
                and response['revision'] != self.state.networks_revision):
            self.state.apply_config(response['revision'], response)
            return True
        return False


class RelayHandler(BaseHTTPRequestHandler):
    "The HTTP request handler of the relay daemon."

    server_version = 'wol-relayd/%s' % __version__
    state = None

    def _authorized(self):
        token = self.state.config.auth_token
        if not token:
            return True
        header = self.headers.get('Authorization') or ''
        return header == 'Bearer %s' % token

    def _send_json(self, payload, status=HTTPStatus.OK):
        body = json.dumps(payload).encode('utf-8')
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def _error(self, message, status=HTTPStatus.BAD_REQUEST):
        self._send_json({'error': message}, status=status)

    def do_GET(self):
        if not self._authorized():
            self._error('unauthorized', status=HTTPStatus.UNAUTHORIZED)
            return
        path = self.path.split('?', 1)[0]
        if path == '/health':
            self._send_json(self.state.health())
        elif path == '/state':
            self._send_json({'neighbors': read_ip_neigh()})
        else:
            self._error('not found', status=HTTPStatus.NOT_FOUND)

    def do_POST(self):
        if not self._authorized():
            self._error('unauthorized', status=HTTPStatus.UNAUTHORIZED)
            return
        if self.path.split('?', 1)[0] != '/wake':
            self._error('not found', status=HTTPStatus.NOT_FOUND)
            return
        length = int(self.headers.get('Content-Length') or 0)
        try:
            payload = json.loads(
                self.rfile.read(length).decode('utf-8') or '{}')
        except (ValueError, UnicodeDecodeError):
            self._error('invalid JSON body')
            return
        mac = normalize_mac(payload.get('mac'))
        if mac is None:
            self._error('invalid MAC address')
            return
        broadcast = payload.get('broadcast')
        try:
            ipaddress.ip_address(broadcast or '')
        except ValueError:
            self._error('invalid broadcast address')
            return
        try:
            sent = self.state.wake(mac, broadcast)
        except ValueError as exc:
            self._error(str(exc))
            return
        except OSError as exc:
            self._error('cannot send packet: %s' % exc,
                status=HTTPStatus.INTERNAL_SERVER_ERROR)
            return
        logger.info(
            'woke %s via %s (%d packets)', mac, broadcast, sent)
        self._send_json({'status': 'sent', 'packets': sent})

    def log_message(self, format, *args):
        logger.debug('%s - %s', self.address_string(), format % args)


def make_server(config, state=None):
    "Return the HTTP server for the configuration."
    state = state or RelayState(config)
    handler = type('BoundRelayHandler', (RelayHandler,), {'state': state})
    server = ThreadingHTTPServer(
        (config.listen_host, config.listen_port), handler)
    server.daemon_threads = True
    return server


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-c', '--config', required=True,
        help='path of the configuration file')
    parser.add_argument('--verbose', action='store_true',
        help='enable debug logging')
    args = parser.parse_args(argv)
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format='%(asctime)s %(levelname)s %(name)s: %(message)s')
    config = RelayConfig.load(args.config)
    if os.geteuid() == 0:
        logger.warning('running as root is not required')
    state = RelayState(config)
    server = make_server(config, state=state)
    if config.config_sync_enabled:
        ConfigSync(config, state).start()
    logger.info(
        'wol-relayd %s listening on %s:%s',
        __version__, config.listen_host, config.listen_port)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()
    return 0


if __name__ == '__main__':
    sys.exit(main())
