#!/usr/bin/env python3
"""Serve the two DTD variants for the XXE/TOCTOU license test.

    python serve.py --mode probe                 # always the "empty" DTD
    python serve.py --mode attack --sequence VP  # verifier first, parser second

Every request is logged with an index, the client address, the path and the
User-Agent, so you can see how many times the iDRAC fetched the DTD and in
which order.

The DTDs are read from this directory on every request, so you can edit
dtd_parser.dtd / dtd_verifier.dtd without restarting the server.
"""
import argparse
import datetime
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

HERE = os.path.dirname(os.path.abspath(__file__))
VARIANTS = {
    "V": "dtd_dur_verifier.dtd",
    "P": "dtd_dur_parser.dtd",
}


class Handler(BaseHTTPRequestHandler):
    server_version = "idrac-dtd/1.0"

    def log_message(self, fmt, *args):
        pass  # we do our own logging

    def setup(self):
        super().setup()
        # Log the raw TCP connection before any HTTP parsing, so a client that
        # connects but sends a malformed request is still visible.
        addr = getattr(self, "client_address", None)
        if addr and addr[0] != "127.0.0.1":
            stamp = datetime.datetime.now().strftime("%H:%M:%S")
            line = f"[{stamp}] CONNECT {addr[0]}:{addr[1]}"
            print(line, flush=True)
            with open(os.path.join(HERE, "requests.log"), "a", encoding="utf-8") as fh:
                fh.write(line + "\n")

    def do_GET(self):
        srv = self.server
        is_dtd = ".dtd" in self.path

        if is_dtd:
            srv.count += 1
            n = srv.count
        else:
            # Any non-DTD GET: log it (iDRAC catalog / share probes) and answer
            # with a tiny XML body so the client gets a real HTTP response.
            if self.client_address[0] != "127.0.0.1":
                stamp = datetime.datetime.now().strftime("%H:%M:%S")
                line = (f"[{stamp}] GET {self.client_address[0]} "
                        f"{self.path!r} (non-dtd) "
                        f"UA={self.headers.get('User-Agent','-')!r}")
                print(line, flush=True)
                with open(os.path.join(HERE, "requests.log"), "a", encoding="utf-8") as fh:
                    fh.write(line + "\n")
            body = b"<Catalog/>\n"
            self.send_response(200)
            self.send_header("Content-Type", "application/xml")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return

        if srv.mode == "probe":
            variant = "V"
        else:
            seq = srv.sequence
            variant = seq[(n - 1) % len(seq)]

        path = os.path.join(HERE, VARIANTS[variant])
        try:
            body = open(path, "rb").read()
        except OSError as e:
            self.send_error(500, str(e))
            return

        stamp = datetime.datetime.now().strftime("%H:%M:%S")
        line = (f"[{stamp}] #{n} {self.client_address[0]} "
                f"{self.path!r} -> {variant} ({VARIANTS[variant]}) "
                f"UA={self.headers.get('User-Agent','-')!r}")
        print(line, flush=True)
        with open(os.path.join(HERE, "requests.log"), "a", encoding="utf-8") as fh:
            fh.write(line + "\n")

        self.send_response(200)
        self.send_header("Content-Type", "application/xml-dtd")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def _log_other(self, method):
        """Log any non-GET request (racadm config export uses PUT/POST)."""
        srv = self.server
        try:
            n = int(self.headers.get("Content-Length", 0) or 0)
        except ValueError:
            n = 0
        body = self.rfile.read(n) if n else b""
        stamp = datetime.datetime.now().strftime("%H:%M:%S")
        line = (f"[{stamp}] {method} {self.client_address[0]} "
                f"{self.path!r} len={len(body)} "
                f"UA={self.headers.get('User-Agent','-')!r}")
        print(line, flush=True)
        with open(os.path.join(HERE, "requests.log"), "a", encoding="utf-8") as fh:
            fh.write(line + "\n")
        self.send_response(200)
        self.send_header("Content-Length", "0")
        self.end_headers()

    def do_PUT(self):
        self._log_other("PUT")

    def do_POST(self):
        self._log_other("POST")

    def do_HEAD(self):
        self._log_other("HEAD")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mode", choices=("probe", "attack"), default="probe")
    ap.add_argument("--sequence", default="VP",
                    help="attack mode: V=verifier(empty), P=parser(Perpetual), "
                         "e.g. VP or PV")
    ap.add_argument("--port", type=int, default=8000)
    ap.add_argument("--bind", default="0.0.0.0")
    a = ap.parse_args()

    srv = ThreadingHTTPServer((a.bind, a.port), Handler)
    srv.mode = a.mode
    srv.sequence = a.sequence.upper()
    srv.count = 0

    print(f"mode={a.mode} sequence={srv.sequence} on http://{a.bind}:{a.port}/license.dtd")
    print("log -> requests.log   (Ctrl-C to stop)", flush=True)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        print("\nstopped", flush=True)


if __name__ == "__main__":
    main()
