#!/usr/bin/env python3
"""Validate the XXE license locally before uploading it.

Checks, for a file produced by build.py:

  1. with dtd_verifier.dtd, the reference digest equals Dell's DigestValue
     (i.e. the verifier will accept the signature);
  2. with dtd_parser.dtd, the term list starts with Perpetual and the element
     is in the licensing namespace.

Usage:
    python check.py forged_perpetual.xml
    python check.py probe_donor.xml
"""
import base64
import hashlib
import os
import sys
import urllib.parse

from lxml import etree

HERE = os.path.dirname(os.path.abspath(__file__))
DS = "http://www.w3.org/2000/09/xmldsig#"
LNS = "http://www.dell.com/2011/12G/licensing"


def parse_with(dtd_name, text):
    start = text.find(b"<!DOCTYPE")
    sysid = text.find(b'SYSTEM "', start)
    if sysid < 0:
        # internal subset: nothing external to rewrite
        t = text
    else:
        dtd = os.path.abspath(os.path.join(HERE, dtd_name))
        url = "file:///" + urllib.parse.quote(dtd.replace("\\", "/"))
        sysid += len(b'SYSTEM "')
        end = text.find(b'"', sysid)
        t = text[:sysid] + url.encode() + text[end:]
    return etree.fromstring(
        t, etree.XMLParser(load_dtd=True, resolve_entities=True, no_network=True)
    )


def digest_of(root):
    doc = etree.fromstring(etree.tostring(root))
    sig = doc.find(f".//{{{DS}}}Signature")
    prev = sig.getprevious()
    if prev is not None:
        prev.tail = (prev.tail or "") + (sig.tail or "")
    sig.getparent().remove(sig)
    return hashlib.sha1(
        etree.tostring(doc, method="c14n", exclusive=False, with_comments=False)
    ).digest()


def main():
    path = sys.argv[1] if len(sys.argv) > 1 else "forged_perpetual.xml"
    d = open(path, "rb").read()

    v = parse_with("dtd_verifier.dtd", d)
    p = parse_with("dtd_parser.dtd", d)

    # the signature is untouched, so the digest is the one in the file
    expected = base64.b64decode(v.find(f".//{{{DS}}}DigestValue").text.strip())

    ok_digest = digest_of(v) == expected
    terms_v = [etree.QName(c).localname for c in v.find(f".//{{{LNS}}}LicenseTerm") if isinstance(c.tag, str)]
    terms_p = [etree.QName(c).localname for c in p.find(f".//{{{LNS}}}LicenseTerm") if isinstance(c.tag, str)]
    first = p.find(f".//{{{LNS}}}LicenseTerm")[0]
    ok_ns = etree.QName(first).namespace == LNS

    print(f"file            : {path}")
    print(f"digest (verifier): {'MATCH' if ok_digest else 'MISMATCH'}")
    print(f"verifier terms  : {terms_v}")
    print(f"parser terms    : {terms_p}")
    print(f"first parser term namespace ok: {ok_ns}")
    print("RESULT:", "PASS" if ok_digest and terms_p[:1] == ["Perpetual"] and ok_ns else "FAIL")
    return 0 if ok_digest else 1


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