/*
 * Copyright (c) RISC OS Developments 2026. All rights reserved.
 * SPDX-License-Identifier: CDDL-1.0
 */

#include "kernel.h"

#include "confirm.h"
#include "manifest.h"
#include "module.h"
#include "policy.h"
#include "sha256.h"

int tlsmanager_upcall_handler(_kernel_swi_regs *registers, void *pw)
{
    const tlsmanager_manifest *manifest;
    const tlsmanager_certchain *certificate;
    const tlsmanager_certchain *top;
    unsigned char fingerprint[TLSMANAGER_SHA256_SIZE];
    int lower_valid;

    (void)pw;
    if(registers->r[0] != TLSMANAGER_UPCALL_CERTIFICATE_CONFIRM)
        return 1;
    manifest = TLSManagerActiveManifest();
    if(!manifest) return 1;

    certificate = (const tlsmanager_certchain *)registers->r[1];
    if(!certificate) return 1;
    lower_valid = 1;
    top = certificate;
    while(top->next)
    {
        if(top->format != TLSMANAGER_UPCALL_FORMAT || top->flags != 0)
            lower_valid = 0;
        top = top->next;
    }
    if(top->format != TLSMANAGER_UPCALL_FORMAT || !top->der || !top->dersize)
        return 1;
    sha256_get_digest(top->der, top->dersize, fingerprint);
    if(TLSManagerPolicyAcceptTop(lower_valid, top->flags, fingerprint,
           (const tlsmanager_anchor *)manifest->anchors,
           manifest->anchor_count, 1))
    {
        TLSManagerRecordAccept(fingerprint);
        registers->r[0] = TLSMANAGER_CONFIRM_ACCEPT;
        return 0;
    }
    return 1;
}
