/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "Licence").
 * You may not use this file except in compliance with the Licence.
 *
 * You can obtain a copy of the licence at @.^.^.LICENSE.
 * See the Licence for the specific language governing permissions
 * and limitations under the Licence.
 *
 * CDDL HEADER END
 *
 * Copyright (c) RISC OS Developments 2026. All rights reserved.
 * SPDX-License-Identifier: CDDL-1.0
 */

/* Pure certificate-flag policy. Certificate parsing, cryptographic chain
   validation and hostname checking remain AcornSSL responsibilities. */

#include <string.h>
#include "policy.h"

static int known_anchor(const unsigned char *fingerprint,
                        const tlsmanager_anchor *anchors,
                        unsigned int count)
{
    unsigned int i;

    for(i = 0; i < count; i++)
        if(memcmp(fingerprint, anchors[i].fingerprint,
                  TLSMANAGER_SHA256_SIZE) == 0) return 1;
    return 0;
}

int TLSManagerPolicyAccept(const tlsmanager_certificate *chain,
                           const tlsmanager_anchor *anchors,
                           unsigned int anchor_count,
                           int manifest_active)
{
    const tlsmanager_certificate *certificate;

    if(!manifest_active || !chain || !anchors || !anchor_count) return 0;

    certificate = chain;
    while(certificate->next)
    {
        if(certificate->flags != 0) return 0;
        certificate = certificate->next;
    }

    return TLSManagerPolicyAcceptTop(1, certificate->flags,
                 certificate->fingerprint, anchors, anchor_count,
                 manifest_active);
}

int TLSManagerPolicyAcceptTop(
    int lower_certificates_valid,
    unsigned int top_flags,
    const unsigned char top_fingerprint[TLSMANAGER_SHA256_SIZE],
    const tlsmanager_anchor *anchors,
    unsigned int anchor_count,
    int manifest_active)
{
    if(!manifest_active || !lower_certificates_valid || !top_fingerprint ||
       !anchors || !anchor_count) return 0;
    if(top_flags != TLSMANAGER_NOT_TRUSTED) return 0;
    return known_anchor(top_fingerprint, anchors, anchor_count);
}
