#!/usr/bin/python3
# Nagios/Icinga plugin to check an iPXE boot menu and every file it boots.
#
# Copyright (c) 2026 Thomas Wagner
# SPDX-License-Identifier: GPL-2.0-or-later

import argparse
import re
import shlex
import ssl
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3

STATE_TEXT = {OK: "OK", WARNING: "WARNING", CRITICAL: "CRITICAL", UNKNOWN: "UNKNOWN"}

VERSION = "0.1"
DEFAULT_TIMEOUT = 10
MAX_DEPTH = 3          # nested scripts followed with --follow
MAX_LISTED = 5         # problems named in the output line

# iPXE commands whose first argument is a file or a URI to fetch. imgexec, imgload and boot are
# left out on purpose: they also take the name of an image that is already loaded.
FETCH_COMMANDS = {"kernel", "initrd", "module", "imgfetch", "chain", "chainload", "sanboot", "sanhook"}
# of these, the ones whose remaining arguments are a command line that may name more files
CMDLINE_COMMANDS = {"kernel", "module", "chain", "chainload"}
# options that take a value, so that the value is not taken for the file
OPTIONS_WITH_VALUE = {"-n", "--name", "-t", "--timeout"}
SAN_OPTIONS_WITH_VALUE = {"-d", "--drive", "-f", "--filename"}

VARIABLE = re.compile(r"\$\{([^}:]+)(?::[A-Za-z0-9_]+)?\}")
SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
URL_IN_TEXT = re.compile(r"https?://[^\s'\"]+")


class PluginError(Exception):
    def __init__(self, state, message):
        super().__init__(message)
        self.state = state
        self.message = message


class ArgumentParser(argparse.ArgumentParser):
    """argparse exits 2 on a usage error, which Nagios reads as CRITICAL; exit UNKNOWN instead."""

    def error(self, message):
        self.print_usage(sys.stderr)
        sys.stderr.write("%s: error: %s\n" % (self.prog, message))
        sys.exit(UNKNOWN)


def human_bytes(value):
    for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
        if value < 1024 or unit == "TiB":
            return "%d B" % value if unit == "B" else "%.1f %s" % (value, unit)
        value /= 1024.0


def build_context(args):
    context = ssl.create_default_context()
    if args.insecure:
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    return context


def request(args, context, url, method, extra=None):
    headers = {"User-Agent": "check_ipxe_menu/%s" % VERSION}
    headers.update(extra or {})
    req = urllib.request.Request(url, method=method, headers=headers)
    return urllib.request.urlopen(req, timeout=args.timeout, context=context)


def fetch_text(args, context, url):
    try:
        with request(args, context, url, "GET") as response:
            return response.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as err:
        raise PluginError(CRITICAL, "menu %s: HTTP %d" % (url, err.code))
    except (urllib.error.URLError, OSError, ValueError) as err:
        raise PluginError(CRITICAL, "menu %s: %s" % (url, getattr(err, "reason", err)))


def probe(args, context, url):
    """Size of the file in bytes (None if the server does not tell), or raise PluginError."""
    last = None
    for method in ("HEAD", "GET"):
        extra = {"Range": "bytes=0-0"} if method == "GET" else None
        try:
            with request(args, context, url, method, extra) as response:
                content_range = response.headers.get("Content-Range", "")
                match = re.match(r"bytes \d+-\d+/(\d+)$", content_range)
                if match:
                    return int(match.group(1))
                length = response.headers.get("Content-Length")
                return int(length) if length is not None else None
        except urllib.error.HTTPError as err:
            last = "HTTP %d" % err.code
            # some servers refuse HEAD; everything else is final
            if method == "HEAD" and err.code in (400, 403, 405, 501):
                continue
            break
        except (urllib.error.URLError, OSError, ValueError) as err:
            last = str(getattr(err, "reason", err))
            break
    raise PluginError(CRITICAL, last)


def split_words(text):
    try:
        return shlex.split(text)
    except ValueError:
        return text.split()


class Menu:
    """What a script says it boots: the files it names, the unresolved ones, the menu entries."""

    def __init__(self, variables):
        self.variables = dict(variables)
        self.files = []       # (url, command)
        self.unresolved = []
        self.skipped = []     # other schemes (tftp, iscsi, ...)
        self.directories = []  # URLs ending in / on a command line
        self.entries = []

    def expand(self, text):
        return VARIABLE.sub(lambda m: self.variables.get(m.group(1), m.group(0)), text)

    def parse(self, text, base):
        for raw in text.splitlines():
            line = raw.strip()
            if not line or line.startswith("#"):
                continue
            for part in re.split(r"\s*(?:&&|\|\|)\s*", line):
                self.command(part.strip(), base)

    def command(self, part, base):
        words = split_words(part)
        if not words:
            return
        name = words[0].lower()
        if name == "set" and len(words) >= 3:
            self.variables[words[1].split(":")[0]] = self.expand(" ".join(words[2:]))
        elif name == "item":
            self.item(words[1:])
        elif name in FETCH_COMMANDS:
            self.fetch(name, words[1:], base)

    def item(self, words):
        i, gap = 0, False
        while i < len(words) and words[i].startswith("-") and words[i] != "--":
            gap = gap or words[i] in ("-g", "--gap")
            i += 2 if words[i] in ("-k", "--key") else 1
        if i < len(words) and words[i] == "--":
            i += 1
        if gap or len(words) <= i:
            return
        label = " ".join(words[i + 1:]) or words[i]
        self.entries.append(self.expand(label))

    def fetch(self, name, words, base):
        with_value = SAN_OPTIONS_WITH_VALUE if name in ("sanboot", "sanhook") else OPTIONS_WITH_VALUE
        positional, i = [], 0
        while i < len(words):
            word = words[i]
            if word.startswith("-") and len(word) > 1:
                i += 2 if (word in with_value) else 1
                continue
            positional.append(word)
            i += 1
        if not positional:
            return
        self.add(self.expand(positional[0]), name, base)
        if name in CMDLINE_COMMANDS:
            for url in URL_IN_TEXT.findall(self.expand(" ".join(positional[1:]))):
                if url.endswith("/"):
                    self.directories.append(url)
                else:
                    self.add(url, name, base)

    def add(self, target, command, base):
        if SCHEME.match(target) and not target.lower().startswith(("http://", "https://")):
            self.skipped.append(target)  # tftp:, iscsi:, ... cannot be checked, variables or not
        elif "${" in target:
            self.unresolved.append(target)
        elif SCHEME.match(target):
            self.files.append((target, command))
        else:
            self.files.append((urllib.parse.urljoin(base, target), command))


def is_script_name(url):
    return urllib.parse.urlsplit(url).path.lower().endswith(".ipxe")


def gather(args, context, url, variables, depth=0, seen=None):
    """Read the script at url (and, with --follow, the scripts it chains to)."""
    seen = seen if seen is not None else set()
    seen.add(url)
    text = fetch_text(args, context, url)
    first = next((line.strip() for line in text.splitlines() if line.strip()), "")
    if not first.lower().startswith("#!ipxe"):
        raise PluginError(CRITICAL, "%s is not an iPXE script (it does not start with #!ipxe)" % url)
    menu = Menu(variables)
    menu.parse(text, url)
    nested = []
    if args.follow and depth < MAX_DEPTH:
        for target, command in menu.files:
            if command in ("chain", "chainload") and is_script_name(target) and target not in seen:
                seen.add(target)
                nested.append(target)
    for target in nested:
        try:
            child = gather(args, context, target, menu.variables, depth + 1, seen)
        except PluginError:
            continue  # reported as a missing file by the file check
        menu.files += child.files
        menu.unresolved += child.unresolved
        menu.skipped += child.skipped
        menu.directories += child.directories
        menu.entries += child.entries
    return menu


def run(args):
    context = build_context(args)
    variables = {}
    for definition in args.define:
        name, sep, value = definition.partition("=")
        if not sep or not name:
            raise PluginError(UNKNOWN, "-D wants NAME=VALUE, got %r" % definition)
        variables[name] = value

    started = time.monotonic()
    menu = gather(args, context, args.url, variables)
    menu_time = time.monotonic() - started

    urls = [url for url, _ in menu.files]
    for directory in menu.directories:
        urls += [directory + name for name in args.dir_file]
    urls += [urllib.parse.urljoin(args.url, extra) for extra in args.also]
    urls = list(dict.fromkeys(urls))
    if not urls and not menu.unresolved:
        raise PluginError(CRITICAL, "menu %s: no boot files found in it" % args.url)

    bad, total = [], 0
    for url in urls:
        try:
            size = probe(args, context, url)
        except PluginError as err:
            bad.append("%s: %s" % (url, err.message))
            continue
        if size == 0:
            bad.append("%s: empty" % url)
        total += size or 0

    perf = ["menu_time=%.3fs;;;0" % menu_time, "files=%d;;;0" % len(urls), "size=%dB;;;0" % total,
            "entries=%d;;;0" % len(menu.entries)]
    detail = ""
    if args.verbose and menu.entries:
        detail = ": " + ", ".join(menu.entries)

    if bad:
        shown = "; ".join(bad[:MAX_LISTED])
        if len(bad) > MAX_LISTED:
            shown += "; and %d more" % (len(bad) - MAX_LISTED)
        return CRITICAL, "%d of %d boot files missing: %s" % (len(bad), len(urls), shown), perf
    unresolved = list(dict.fromkeys(menu.unresolved))
    if unresolved:
        shown = ", ".join(unresolved[:MAX_LISTED])
        return (WARNING, "%d file(s) not checked, they contain variables (define them with -D): %s"
                % (len(unresolved), shown), perf)
    message = "menu with %d entries and all %d boot files there (%s)%s" % (
        len(menu.entries), len(urls), human_bytes(total), detail)
    return OK, message, perf


def build_parser():
    parser = ArgumentParser(
        prog="check_ipxe_menu",
        description="Nagios/Icinga plugin that fetches an iPXE menu and checks, with HEAD requests, "
                    "that every kernel, initrd, image and boot loader it names is on the server.",
    )
    parser.add_argument("-V", "--version", action="version", version="check_ipxe_menu %s" % VERSION)
    parser.add_argument("-u", "--url", required=True,
                        help="URL of the iPXE script, e.g. http://boot.example.com/boot.ipxe")
    parser.add_argument("-t", "--timeout", type=float, default=DEFAULT_TIMEOUT,
                        help="timeout of each request in seconds (default: %d)" % DEFAULT_TIMEOUT)
    parser.add_argument("-k", "--insecure", action="store_true", help="do not verify the TLS certificate")
    parser.add_argument("-D", "--define", action="append", default=[], metavar="NAME=VALUE",
                        help="value of an iPXE variable the script does not set itself, e.g. next-server; "
                             "can be repeated")
    parser.add_argument("--follow", action="store_true",
                        help="also read the .ipxe scripts the menu chains to (up to %d levels)" % MAX_DEPTH)
    parser.add_argument("--dir-file", action="append", default=[], metavar="FILE",
                        help="for every URL ending in / on a kernel command line, also check this file below "
                             "it, e.g. sysresccd/x86_64/airootfs.sfs for SystemRescue; can be repeated")
    parser.add_argument("--also", action="append", default=[], metavar="URL",
                        help="check this file too, relative to the menu or absolute; can be repeated")
    parser.add_argument("-v", "--verbose", action="store_true", help="list the menu entries in the output")
    return parser


def main():
    args = build_parser().parse_args()
    try:
        state, message, perf = run(args)
    except PluginError as err:
        print("IPXE MENU %s - %s" % (STATE_TEXT[err.state], err.message))
        return err.state
    print("IPXE MENU %s - %s | %s" % (STATE_TEXT[state], message, " ".join(perf)))
    return state


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(UNKNOWN)
