#!/usr/bin/env python3
"""TLS checks of BNC's Ntrip 2s client and upload (option sslIgnoreErrors,
CA certificate path, client certificate) against tools/fakecaster.py.

BNC uploads with Ntrip 2s always to port 443, so the checks run in an
unprivileged user and network namespace (unshare -rn), where binding port 443
is allowed and nothing leaves the machine. Certificates are created with
openssl in tests/work/ssl_check/.

    tests/tools/ssl_check.py [--bnc PATH]      exit code 1 if a check fails

Checks (host name localhost, self-signed test CA):
  upload  : server certificate of an unknown CA is rejected / accepted with
            the CA in 'sslCaCertPath' / accepted with sslIgnoreErrors, the
            ignored errors being logged; certificate for another host name
            rejected; client certificate presented also with sslIgnoreErrors
  download: unknown CA rejected / accepted with the CA / with sslIgnoreErrors
"""

import argparse
import glob
import os
import shutil
import subprocess
import sys

TOOLS = os.path.dirname(os.path.abspath(__file__))
TESTS = os.path.dirname(TOOLS)
ROOT = os.path.dirname(TESTS)
WORK = os.path.join(TESTS, "work", "ssl_check")
UPLOAD_RAW = os.path.join(TESTS, "data", "upload_rtnet_5min.raw")
SERVE_RAW = os.path.join(TESTS, "data", "crafted_limits.raw")


def sh(*cmd):
    subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def make_certs(d):
    os.makedirs(d)
    sh("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "30",
       "-subj", "/CN=BNC Test CA", "-keyout", d + "/ca.key", "-out", d + "/ca.crt")

    def signed(name, cn, san, ext="serverAuth"):
        with open(d + "/" + name + ".ext", "w") as f:
            f.write("subjectAltName=%s\nextendedKeyUsage=%s\n" % (san, ext))
        sh("openssl", "genrsa", "-traditional", "-out", d + "/" + name + ".key", "2048")
        sh("openssl", "req", "-new", "-key", d + "/" + name + ".key", "-subj", "/CN=" + cn,
           "-out", d + "/" + name + ".csr")
        sh("openssl", "x509", "-req", "-in", d + "/" + name + ".csr", "-CA", d + "/ca.crt",
           "-CAkey", d + "/ca.key", "-CAcreateserial", "-days", "30",
           "-extfile", d + "/" + name + ".ext", "-out", d + "/" + name + ".crt")

    signed("server", "localhost", "DNS:localhost,IP:127.0.0.1")
    signed("other", "other.example", "DNS:other.example")
    signed("client", "bnc-client", "DNS:bnc-client", "clientAuth")
    os.makedirs(d + "/cadir")
    shutil.copy(d + "/ca.crt", d + "/cadir/ca.crt")
    os.makedirs(d + "/emptydir")
    # client certificate naming convention of BNC: <host>.<port>.crt/.key
    os.makedirs(d + "/clientdir")
    shutil.copy(d + "/client.crt", d + "/clientdir/localhost.443.crt")
    shutil.copy(d + "/client.key", d + "/clientdir/localhost.443.key")


def run(bnc, name, certs, server, caster_args, bnc_args, live):
    """Start the fake caster on 443, run BNC; returns (caster output, BNC log)."""
    d = os.path.join(WORK, name)
    os.makedirs(os.path.join(d, "Output"))
    os.symlink(os.path.join(ROOT, "Example_Configs", "Input"), os.path.join(d, "Input"))
    fc = subprocess.Popen(
        [sys.executable, "-I", os.path.join(TOOLS, "fakecaster.py"), "--port", "443",
         "--out", os.path.join(d, "Output", "upload.raw"), "--sta", "SSL",
         "--time", "2026-10-01T09:33:00", "--timeout", "8",
         "--tls-cert", certs + "/" + server + ".crt", "--tls-key", certs + "/" + server + ".key"]
        + caster_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    fc.stdout.readline()  # "listening"
    env = dict(os.environ, QT_QPA_PLATFORM="offscreen", LC_ALL="C", TZ="UTC")
    cmd = [bnc, "--nw", "--platform", "offscreen"] + bnc_args
    with open(os.path.join(d, "bnc.out"), "wb") as out:
        if live:  # Ntrip client: runs until stopped
            p = subprocess.Popen(cmd, cwd=d, stdout=out, stderr=subprocess.STDOUT, env=env)
            try:
                p.wait(12)
            except subprocess.TimeoutExpired:
                p.send_signal(2)
                p.wait(30)
        else:
            subprocess.run(cmd, cwd=d, stdout=out, stderr=subprocess.STDOUT, env=env, timeout=300)
    caster = fc.communicate(timeout=120)[0]
    log = ""
    for f in sorted(glob.glob(os.path.join(d, "Output", "*.log*"))):
        with open(f, errors="replace") as inp:
            log += inp.read()
    with open(os.path.join(d, "caster.out"), "w") as f:
        f.write(caster)
    return caster, log


def upload(bnc, name, certs, server="server", ignore=0, cadir="emptydir", clientdir="emptydir",
           caster_args=()):
    mp = ("localhost,443,CLOCK,2s,user,pass,IGS20,IGS-SSR,0,,,,,,,0 byte(s),")
    return run(bnc, name, certs, server, list(caster_args),
               ["--conf", os.path.join(ROOT, "Example_Configs", "16_Upload.bnc"),
                "--file", UPLOAD_RAW,
                "-key", "uploadMountpointsOut", mp,
                "-key", "sslIgnoreErrors", str(ignore),
                "-key", "sslCaCertPath", certs + "/" + cadir,
                "-key", "sslClientCertPath", certs + "/" + clientdir + "/"], live=False)


def download(bnc, name, certs, ignore=0, cadir="emptydir"):
    return run(bnc, name, certs, "server", ["--serve", SERVE_RAW],
               ["--conf", os.path.join(ROOT, "Example_Configs", "22_Empty.bnc"),
                "-key", "mountPoints", "//user:pass@localhost:443/TEST RTCM_3 DEU 50.00 8.00 no 2s",
                "-key", "logFile", "Output/bnc.log",
                "-key", "sslIgnoreErrors", str(ignore),
                "-key", "sslCaCertPath", certs + "/" + cadir], live=True)


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--bnc", default=os.path.join(ROOT, "bnc"))
    args = ap.parse_args()
    bnc = os.path.abspath(args.bnc)

    if os.environ.get("BNC_SSL_CHECK_NS") != "1":
        # re-run inside a new user + network namespace
        env = dict(os.environ, BNC_SSL_CHECK_NS="1")
        return subprocess.run(["unshare", "-rn", "sh", "-c",
                               'ip link set lo up && exec "$@"', "sh",
                               sys.executable, "-I", os.path.abspath(__file__), "--bnc", bnc],
                              env=env).returncode

    shutil.rmtree(WORK, ignore_errors=True)
    certs = os.path.join(WORK, "certs")
    make_certs(certs)

    failed = 0

    def check(name, ok, detail):
        nonlocal failed
        print("%-6s %-40s %s" % ("PASS" if ok else "FAIL", name, detail), flush=True)
        failed += not ok

    def received(caster):
        for line in caster.splitlines():
            if line.startswith("received "):
                return int(line.split()[1])
        return 0

    def served(caster):
        for line in caster.splitlines():
            if line.startswith("served "):
                return int(line.split()[1])
        return 0

    c, log = upload(bnc, "up_unknown_ca", certs)
    check("upload: unknown CA rejected", received(c) == 0 and "SSL Error" in log
          and "ignored" not in log, "%d bytes received" % received(c))

    c, log = upload(bnc, "up_ca", certs, cadir="cadir")
    check("upload: CA in sslCaCertPath accepted", received(c) > 0 and "SSL Error" not in log,
          "%d bytes received" % received(c))

    c, log = upload(bnc, "up_ignore", certs, ignore=2)
    check("upload: sslIgnoreErrors, errors logged", received(c) > 0 and "(ignored as configured)" in log,
          "%d bytes received" % received(c))

    c, log = upload(bnc, "up_other_host", certs, server="other", cadir="cadir")
    check("upload: other host name rejected", received(c) == 0 and "SSL Error" in log,
          "%d bytes received" % received(c))

    c, log = upload(bnc, "up_client_cert", certs, cadir="cadir", clientdir="clientdir",
                    caster_args=["--tls-client-ca", certs + "/ca.crt"])
    check("upload: client certificate", received(c) > 0, "%d bytes received" % received(c))

    c, log = upload(bnc, "up_client_cert_ignore", certs, ignore=2, clientdir="clientdir",
                    caster_args=["--tls-client-ca", certs + "/ca.crt"])
    check("upload: client certificate, sslIgnoreErrors", received(c) > 0,
          "%d bytes received" % received(c))

    c, log = download(bnc, "down_unknown_ca", certs)
    check("download: unknown CA rejected", served(c) == 0 and "SSL Error" in log
          and "ignored" not in log, "%d bytes served" % served(c))

    c, log = download(bnc, "down_ca", certs, cadir="cadir")
    check("download: CA in sslCaCertPath accepted", served(c) > 0 and "Get data" in log,
          "%d bytes served" % served(c))

    c, log = download(bnc, "down_ignore", certs, ignore=2)
    check("download: sslIgnoreErrors, errors logged", served(c) > 0 and "Get data" in log
          and "(ignored as configured)" in log, "%d bytes served" % served(c))

    print("%d check(s) failed, details in %s" % (failed, os.path.relpath(WORK, ROOT)))
    return 1 if failed else 0


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