#!/usr/bin/env python3
"""Publish verified Critical Pro text feeds for a private appliance relay. GPL-3.0-only."""

import base64
from contextlib import closing
import fcntl
import hashlib
from http.client import HTTPException
import ipaddress
import json
import os
from pathlib import Path
import re
import shutil
import sys
import tempfile
from urllib.error import HTTPError
from urllib.request import build_opener, HTTPRedirectHandler, ProxyHandler, Request

ORIGIN = 'https://feeds.data-shield.eu'
PREFIX = '/feeds/critical/'
FULL = 'prod_critical_data-shield_ipv4_blocklist.txt'
GENERATION = re.compile(r'[0-9]{8}T[0-9]{6}Z-[a-f0-9]{12}')
LIMIT = 12 * 1024 * 1024


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *args):
        raise ValueError('Unexpected redirect from the feed origin')


def downloader(credential):
    if credential is None:
        # A root launcher opens the private file before dropping to the relay user.
        raw = sys.stdin.buffer.read(257)
        if len(raw) > 256:
            raise ValueError('Device credential exceeds the size limit')
        fields = raw.decode('ascii').splitlines()
    else:
        fields = credential.read_text(encoding='ascii').splitlines()
    if (len(fields) != 2 or not re.fullmatch(r'[0-9a-f]{32}', fields[0])
            or not re.fullmatch(r'[A-Za-z0-9_-]{20,128}', fields[1])):
        raise ValueError('Device credential file must contain the Device ID and token on separate lines')
    header = 'Basic ' + base64.b64encode(':'.join(fields).encode('ascii')).decode('ascii')
    opener = build_opener(ProxyHandler({}), NoRedirect())

    def fetch(path, limit):
        # Callers construct every path from strict names. Never follow a supplied URL.
        request = Request(ORIGIN + path, headers={'Authorization': header, 'Accept-Encoding': 'identity'})
        with closing(opener.open(request, timeout=45)) as response:
            if response.status != 200 or response.geturl() != request.full_url:
                raise ValueError('Unexpected HTTPS response')
            raw = response.read(limit + 1)
        if len(raw) > limit:
            raise ValueError('Upstream response exceeds its size limit')
        return raw

    return fetch


def metadata(raw):
    doc = json.loads(raw)
    generation = doc['generation']
    if not isinstance(generation, str) or not GENERATION.fullmatch(generation):
        raise ValueError('Invalid feed generation')
    files = doc['files']
    if not isinstance(files, list) or not 2 <= len(files) <= 677:
        raise ValueError('Invalid number of feed files')
    for index, item in enumerate(files):
        if index:
            high, low = divmod(index - 1, 26)
            suffix = chr(97 + high) + chr(97 + low)
            name = 'prod_critical_' + suffix + '_data-shield_ipv4_blocklist.txt'
        else:
            name = FULL
        if (item['name'] != name or item['url'] != PREFIX + generation + '/' + name
                or type(item['bytes']) is not int or not 1 <= item['bytes'] <= LIMIT
                or type(item['records']) is not int or not 1 <= item['records'] <= (30000 if index else LIMIT)
                or not isinstance(item['sha256'], str) or not re.fullmatch('[0-9a-f]{64}', item['sha256'])):
            raise ValueError('Invalid manifest file metadata')
    for key in ('records', 'bytes'):
        if sum(item[key] for item in files[1:]) != files[0][key]:
            raise ValueError('Manifest totals do not match its splits')
    return generation, files


def stage(directory, files, fetch):
    digest = hashlib.sha256()
    previous = -1
    with (directory / 'critical.txt').open('xb') as full:
        for item in files[1:]:
            data = fetch(item['url'], item['bytes'])
            if (len(data) != item['bytes'] or hashlib.sha256(data).hexdigest() != item['sha256']
                    or not data.endswith(b'\n') or data.count(b'\n') != item['records']):
                raise ValueError('Split content does not match the manifest')
            for entry in data[:-1].split(b'\n'):
                address = ipaddress.IPv4Address(entry.decode('ascii'))
                if str(address).encode('ascii') != entry or int(address) <= previous:
                    raise ValueError('Expected canonical, strictly increasing IPv4 records')
                previous = int(address)
            suffix = item['name'][len('prod_critical_'):len('prod_critical_') + 2]
            (directory / ('critical-' + suffix + '.txt')).write_bytes(data)
            full.write(data)
            digest.update(data)
    if digest.hexdigest() != files[0]['sha256']:
        raise ValueError('Combined splits do not match the complete feed')


def publish(state, fetch):
    with (state / '.refresh.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        generation, files = metadata(fetch(PREFIX + 'manifest.json', 512 * 1024))
        current = state / 'current'
        prior = os.readlink(current) if current.is_symlink() else None
        if prior:
            match = re.fullmatch(r'snapshot-(' + GENERATION.pattern + r')-[a-z0-9_]+', prior)
            if not match:
                raise ValueError('Unexpected active snapshot path')
            old = match[1]
            if generation != old and generation[:16] <= old[:16]:
                raise ValueError('Upstream generation is older or conflicts with the active generation')
        staging = Path(tempfile.mkdtemp(prefix='snapshot-' + generation + '-', dir=state))
        link = staging / '.activate'
        try:
            stage(staging, files, fetch)
            staging.chmod(0o750)
            link.symlink_to(staging.name)
            os.replace(link, current)
        except BaseException:
            shutil.rmtree(staging)
            raise
        # Keep the prior directory available to reads already in progress.
        for directory in state.glob('snapshot-*'):
            if (directory.name not in (prior, staging.name) and not directory.is_symlink()
                    and re.fullmatch(r'snapshot-' + GENERATION.pattern + r'-[a-z0-9_]+', directory.name)
                    and directory.is_dir()):
                shutil.rmtree(directory)
        return generation, len(files) - 1, files[0]['records']


def main():
    os.umask(0o027)
    try:
        state = Path(os.environ['STATE_DIRECTORY'])
        if sys.argv[1:] == ['--credential-stdin']:
            credential = None
        elif not sys.argv[1:]:
            credential = Path(os.environ['CREDENTIALS_DIRECTORY']) / 'device'
        else:
            sys.exit('Usage: refresh.py [--credential-stdin]')
        generation, splits, count = publish(state, downloader(credential))
    except HTTPError as error:
        sys.exit(f'Feed origin returned HTTP {error.code}. Check the device credential and service status.')
    except (OSError, HTTPException, ValueError, KeyError, TypeError) as error:
        sys.exit('Relay refresh failed: ' + type(error).__name__ + '. Check network, TLS, inputs and storage.')
    print(f'Published generation {generation} with {count} IPv4 addresses and {splits} splits.')


if __name__ == '__main__':
    main()
