/*
 * Copyright 2024-2026 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */
/* clang-format off */

/* clang-format on */

#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/err.h>
#include <openssl/param_build.h>
#include <openssl/params.h>
#include <openssl/proverr.h>
#include <openssl/rand.h>
#include <openssl/self_test.h>
#include "internal/nelem.h"
#include "internal/param_build_set.h"
#include "prov/implementations.h"
#include "prov/mlx_kem.h"
#include "prov/provider_ctx.h"
#include "prov/providercommon.h"
#include "prov/securitycheck.h"

static OSSL_FUNC_keymgmt_gen_fn mlx_kem_gen;
static OSSL_FUNC_keymgmt_gen_cleanup_fn mlx_kem_gen_cleanup;
static OSSL_FUNC_keymgmt_gen_set_params_fn mlx_kem_gen_set_params;
static OSSL_FUNC_keymgmt_gen_settable_params_fn mlx_kem_gen_settable_params;
static OSSL_FUNC_keymgmt_get_params_fn mlx_kem_get_params;
static OSSL_FUNC_keymgmt_gettable_params_fn mlx_kem_gettable_params;
static OSSL_FUNC_keymgmt_set_params_fn mlx_kem_set_params;
static OSSL_FUNC_keymgmt_settable_params_fn mlx_kem_settable_params;
static OSSL_FUNC_keymgmt_has_fn mlx_kem_has;
static OSSL_FUNC_keymgmt_match_fn mlx_kem_match;
static OSSL_FUNC_keymgmt_import_fn mlx_kem_import;
static OSSL_FUNC_keymgmt_export_fn mlx_kem_export;
static OSSL_FUNC_keymgmt_import_types_fn mlx_kem_imexport_types;
static OSSL_FUNC_keymgmt_export_types_fn mlx_kem_imexport_types;
static OSSL_FUNC_keymgmt_dup_fn mlx_kem_dup;

static const int minimal_selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
    | OSSL_KEYMGMT_SELECT_PRIVATE_KEY;

/* Must match DECLARE_DISPATCH invocations at the end of the file */
static const ECDH_VINFO hybrid_vtable[] = {
    { "EC", "P-256", 65, 32, 32, 1, EVP_PKEY_ML_KEM_768 },
    { "EC", "P-384", 97, 48, 48, 1, EVP_PKEY_ML_KEM_1024 },
#if !defined(OPENSSL_NO_ECX)
    { "X25519", NULL, 32, 32, 32, 0, EVP_PKEY_ML_KEM_768 },
    { "X448", NULL, 56, 56, 56, 0, EVP_PKEY_ML_KEM_1024 },
#endif
};

typedef struct mlx_kem_gen_ctx_st {
    OSSL_LIB_CTX *libctx;
    char *propq;
    int selection;
    unsigned int evp_type;
} PROV_ML_KEM_GEN_CTX;

static void mlx_kem_key_free(void *vkey)
{
    MLX_KEY *key = vkey;

    if (key == NULL)
        return;
    OPENSSL_free(key->propq);
    EVP_PKEY_free(key->mkey);
    EVP_PKEY_free(key->xkey);
    OPENSSL_free(key);
}

/* Takes ownership of propq */
static void *
mlx_kem_key_new(unsigned int v, OSSL_LIB_CTX *libctx, char *propq)
{
    MLX_KEY *key = NULL;
    unsigned int ml_kem_variant;

    if (!ossl_prov_is_running()
        || v >= OSSL_NELEM(hybrid_vtable)
        || (key = OPENSSL_malloc(sizeof(*key))) == NULL)
        goto err;

    ml_kem_variant = hybrid_vtable[v].ml_kem_variant;
    key->libctx = libctx;
    key->minfo = ossl_ml_kem_get_vinfo(ml_kem_variant);
    key->xinfo = &hybrid_vtable[v];
    key->xkey = key->mkey = NULL;
    key->state = MLX_HAVE_NOKEYS;
    key->propq = propq;
    return key;

err:
    OPENSSL_free(propq);
    return NULL;
}

static int mlx_kem_has(const void *vkey, int selection)
{
    const MLX_KEY *key = vkey;

    /* A NULL key MUST fail to have anything */
    if (!ossl_prov_is_running() || key == NULL)
        return 0;

    switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) {
    case 0:
        return 1;
    case OSSL_KEYMGMT_SELECT_PUBLIC_KEY:
        return mlx_kem_have_pubkey(key);
    default:
        return mlx_kem_have_prvkey(key);
    }
}

static int mlx_kem_match(const void *vkey1, const void *vkey2, int selection)
{
    const MLX_KEY *key1 = vkey1;
    const MLX_KEY *key2 = vkey2;
    int have_pub1 = mlx_kem_have_pubkey(key1);
    int have_pub2 = mlx_kem_have_pubkey(key2);

    if (!ossl_prov_is_running())
        return 0;

    /* Compare domain parameters */
    if (key1->xinfo != key2->xinfo)
        return 0;

    if (!(selection & OSSL_KEYMGMT_SELECT_KEYPAIR))
        return 1;

    if (have_pub1 ^ have_pub2)
        return 0;

    /* As in other providers, equal when both have no key material. */
    if (!have_pub1)
        return 1;

    return EVP_PKEY_eq(key1->mkey, key2->mkey)
        && EVP_PKEY_eq(key1->xkey, key2->xkey);
}

/* clang-format off */
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
#ifndef ml_kem_import_export_list
static const OSSL_PARAM ml_kem_import_export_list[] = {
    OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
    OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0),
    OSSL_PARAM_END
};
#endif

#ifndef ml_kem_import_export_st
struct ml_kem_import_export_st {
    OSSL_PARAM *privkey;
    OSSL_PARAM *pubkey;
};
#endif

#ifndef ml_kem_import_export_decoder
static int ml_kem_import_export_decoder
    (const OSSL_PARAM *p, struct ml_kem_import_export_st *r)
{
    const char *s;

    memset(r, 0, sizeof(*r));
    if (p != NULL)
        for (; (s = p->key) != NULL; p++)
            switch(s[0]) {
            default:
                break;
            case 'p':
                switch(s[1]) {
                default:
                    break;
                case 'r':
                    if (ossl_likely(strcmp("iv", s + 2) == 0)) {
                        /* OSSL_PKEY_PARAM_PRIV_KEY */
                        if (ossl_unlikely(r->privkey != NULL)) {
                            ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                           "param %s is repeated", s);
                            return 0;
                        }
                        r->privkey = (OSSL_PARAM *)p;
                    }
                    break;
                case 'u':
                    if (ossl_likely(strcmp("b", s + 2) == 0)) {
                        /* OSSL_PKEY_PARAM_PUB_KEY */
                        if (ossl_unlikely(r->pubkey != NULL)) {
                            ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                           "param %s is repeated", s);
                            return 0;
                        }
                        r->pubkey = (OSSL_PARAM *)p;
                    }
                }
            }
    return 1;
}
#endif
/* End of machine generated */
/* clang-format on */

typedef struct export_cb_arg_st {
    const char *algorithm_name;
    uint8_t *pubenc;
    uint8_t *prvenc;
    int pubcount;
    int prvcount;
    size_t puboff;
    size_t prvoff;
    size_t publen;
    size_t prvlen;
} EXPORT_CB_ARG;

/* Copy any exported key material into its storage slot */
static int export_sub_cb(const OSSL_PARAM *params, void *varg)
{
    EXPORT_CB_ARG *sub_arg = varg;
    struct ml_kem_import_export_st p;
    size_t len;

    if (!ml_kem_import_export_decoder(params, &p))
        return 0;

    /*
     * The caller will decide whether anything essential is missing, but, if
     * some key material was returned, it should have the right (parameter)
     * data type and length.
     */
    if (sub_arg->pubenc != NULL && p.pubkey != NULL) {
        void *pub = sub_arg->pubenc + sub_arg->puboff;

        if (OSSL_PARAM_get_octet_string(p.pubkey, &pub, sub_arg->publen, &len) != 1)
            return 0;
        if (len != sub_arg->publen) {
            ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,
                "Unexpected %s public key length %lu != %lu",
                sub_arg->algorithm_name, (unsigned long)len,
                sub_arg->publen);
            return 0;
        }
        ++sub_arg->pubcount;
    }
    if (sub_arg->prvenc != NULL && p.privkey != NULL) {
        void *prv = sub_arg->prvenc + sub_arg->prvoff;

        if (OSSL_PARAM_get_octet_string(p.privkey, &prv, sub_arg->prvlen, &len) != 1)
            return 0;
        if (len != sub_arg->prvlen) {
            ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,
                "Unexpected %s private key length %lu != %lu",
                sub_arg->algorithm_name, (unsigned long)len,
                (unsigned long)sub_arg->publen);
            return 0;
        }
        ++sub_arg->prvcount;
    }
    return 1;
}

static int
export_sub(EXPORT_CB_ARG *sub_arg, int selection, MLX_KEY *key)
{
    int slot;

    /*
     * The caller is responsible for initialising only the pubenc and prvenc
     * pointer fields, the rest are set here or in the callback.
     */
    sub_arg->pubcount = 0;
    sub_arg->prvcount = 0;

    for (slot = 0; slot < 2; ++slot) {
        int ml_kem_slot = key->xinfo->ml_kem_slot;
        EVP_PKEY *pkey;

        /* Export the parts of each component into its storage slot */
        if (slot == ml_kem_slot) {
            pkey = key->mkey;
            sub_arg->algorithm_name = key->minfo->algorithm_name;
            sub_arg->puboff = slot * key->xinfo->pubkey_bytes;
            sub_arg->prvoff = slot * key->xinfo->prvkey_bytes;
            sub_arg->publen = key->minfo->pubkey_bytes;
            sub_arg->prvlen = key->minfo->prvkey_bytes;
        } else {
            pkey = key->xkey;
            sub_arg->algorithm_name = key->xinfo->algorithm_name;
            sub_arg->puboff = (1 - ml_kem_slot) * key->minfo->pubkey_bytes;
            sub_arg->prvoff = (1 - ml_kem_slot) * key->minfo->prvkey_bytes;
            sub_arg->publen = key->xinfo->pubkey_bytes;
            sub_arg->prvlen = key->xinfo->prvkey_bytes;
        }
        if (!EVP_PKEY_export(pkey, selection, export_sub_cb, (void *)sub_arg))
            return 0;
    }
    return 1;
}

static int mlx_kem_export(void *vkey, int selection, OSSL_CALLBACK *param_cb,
    void *cbarg)
{
    MLX_KEY *key = vkey;
    OSSL_PARAM_BLD *tmpl = NULL;
    OSSL_PARAM *params = NULL, *p;
    size_t publen;
    size_t prvlen;
    int ret = 0;
    EXPORT_CB_ARG sub_arg;

    if (!ossl_prov_is_running() || key == NULL)
        return 0;

    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
        return 0;

    /* Fail when no key material has yet been provided */
    if (!mlx_kem_have_pubkey(key)) {
        ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
        return 0;
    }
    publen = key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes;
    prvlen = key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes;
    memset(&sub_arg, 0, sizeof(sub_arg));

    if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
        sub_arg.pubenc = OPENSSL_malloc(publen);
        if (sub_arg.pubenc == NULL)
            goto err;
    }

    if (mlx_kem_have_prvkey(key)
        && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
        /*
         * Allocated on the secure heap if configured, this is detected in
         * ossl_param_build_set_octet_string(), which will then also use the
         * secure heap.
         */
        sub_arg.prvenc = OPENSSL_secure_zalloc(prvlen);
        if (sub_arg.prvenc == NULL)
            goto err;
    }

    tmpl = OSSL_PARAM_BLD_new();
    if (tmpl == NULL)
        goto err;

    /* Extract sub-component key material */
    if (!export_sub(&sub_arg, selection, key))
        goto err;

    if (sub_arg.pubenc != NULL && sub_arg.pubcount == 2
        && !ossl_param_build_set_octet_string(
            tmpl, NULL, OSSL_PKEY_PARAM_PUB_KEY, sub_arg.pubenc, publen))
        goto err;

    if (sub_arg.prvenc != NULL && sub_arg.prvcount == 2
        && !ossl_param_build_set_octet_string(
            tmpl, NULL, OSSL_PKEY_PARAM_PRIV_KEY, sub_arg.prvenc, prvlen))
        goto err;

    params = OSSL_PARAM_BLD_to_param(tmpl);
    if (params == NULL)
        goto err;

    ret = param_cb(params, cbarg);
    /*
     * OSSL_PARAM_free() only wipes the secure-heap data block,
     * so wipe the key material copies held in the params first.
     */
    for (p = params; p->key != NULL; p++)
        OPENSSL_cleanse(p->data, p->data_size);
    OSSL_PARAM_free(params);

err:
    OSSL_PARAM_BLD_free(tmpl);
    OPENSSL_secure_clear_free(sub_arg.prvenc, prvlen);
    OPENSSL_clear_free(sub_arg.pubenc, publen);
    return ret;
}

static const OSSL_PARAM *mlx_kem_imexport_types(int selection)
{
    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0)
        return ml_kem_import_export_list;
    return NULL;
}

static int
load_slot(OSSL_LIB_CTX *libctx, const char *propq, const char *pname,
    int selection, MLX_KEY *key, int slot, const uint8_t *in,
    int mbytes, int xbytes)
{
    EVP_PKEY_CTX *ctx;
    EVP_PKEY **ppkey;
    OSSL_PARAM parr[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
    const char *alg;
    char *group = NULL;
    size_t off, len;
    void *val;
    int ml_kem_slot = key->xinfo->ml_kem_slot;
    int ret = 0;

    if (slot == ml_kem_slot) {
        alg = key->minfo->algorithm_name;
        ppkey = &key->mkey;
        off = slot * xbytes;
        len = mbytes;
    } else {
        alg = key->xinfo->algorithm_name;
        group = (char *)key->xinfo->group_name;
        ppkey = &key->xkey;
        off = (1 - ml_kem_slot) * mbytes;
        len = xbytes;
    }
    val = (void *)(in + off);

    if ((ctx = EVP_PKEY_CTX_new_from_name(libctx, alg, propq)) == NULL
        || EVP_PKEY_fromdata_init(ctx) <= 0)
        goto err;
    parr[0] = OSSL_PARAM_construct_octet_string(pname, val, len);
    if (group != NULL)
        parr[1] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
            group, 0);
    if (EVP_PKEY_fromdata(ctx, ppkey, selection, parr) > 0)
        ret = 1;

err:
    EVP_PKEY_CTX_free(ctx);
    return ret;
}

static int
load_keys(MLX_KEY *key,
    const uint8_t *pubenc, size_t publen,
    const uint8_t *prvenc, size_t prvlen)
{
    int slot;

    for (slot = 0; slot < 2; ++slot) {
        if (prvlen) {
            /* Ignore public keys when private provided */
            if (!load_slot(key->libctx, key->propq, OSSL_PKEY_PARAM_PRIV_KEY,
                    minimal_selection, key, slot, prvenc,
                    (int)key->minfo->prvkey_bytes,
                    (int)key->xinfo->prvkey_bytes))
                goto err;
        } else if (publen) {
            /* Absent private key data, import public keys */
            if (!load_slot(key->libctx, key->propq, OSSL_PKEY_PARAM_PUB_KEY,
                    minimal_selection, key, slot, pubenc,
                    (int)key->minfo->pubkey_bytes,
                    (int)key->xinfo->pubkey_bytes))
                goto err;
        }
    }
    key->state = prvlen ? MLX_HAVE_PRVKEY : MLX_HAVE_PUBKEY;
    return 1;

err:
    EVP_PKEY_free(key->mkey);
    EVP_PKEY_free(key->xkey);
    key->xkey = key->mkey = NULL;
    key->state = MLX_HAVE_NOKEYS;
    return 0;
}

static int mlx_kem_key_fromdata(MLX_KEY *key,
    const OSSL_PARAM params[],
    int include_private)
{
    struct ml_kem_import_export_st p;
    const void *pubenc = NULL, *prvenc = NULL;
    size_t pubkey_bytes, prvkey_bytes;
    size_t publen = 0, prvlen = 0;

    /* Invalid attempt to mutate a key, what is the right error to report? */
    if (key == NULL || mlx_kem_have_pubkey(key))
        return 0;
    pubkey_bytes = key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes;
    prvkey_bytes = key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes;

    if (!ml_kem_import_export_decoder(params, &p))
        return 0;

    /* What does the caller want to set? */
    if (p.pubkey != NULL && OSSL_PARAM_get_octet_string_ptr(p.pubkey, &pubenc, &publen) != 1)
        return 0;
    if (include_private
        && p.privkey != NULL
        && OSSL_PARAM_get_octet_string_ptr(p.privkey, &prvenc, &prvlen) != 1)
        return 0;

    /* The caller MUST specify at least one of the public or private keys. */
    if (publen == 0 && prvlen == 0) {
        ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
        return 0;
    }

    /*
     * When a pubkey is provided, its length MUST be correct, if a private key
     * is also provided, the public key will be otherwise ignored.  We could
     * look for a matching encoded block, but unclear this is useful.
     */
    if (publen != 0 && publen != pubkey_bytes) {
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
        return 0;
    }
    if (prvlen != 0 && prvlen != prvkey_bytes) {
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
        return 0;
    }

    return load_keys(key, pubenc, publen, prvenc, prvlen);
}

static int mlx_kem_import(void *vkey, int selection, const OSSL_PARAM params[])
{
    MLX_KEY *key = vkey;
    int include_private;

    if (!ossl_prov_is_running() || key == NULL)
        return 0;

    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
        return 0;

    include_private = selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
    return mlx_kem_key_fromdata(key, params, include_private);
}

/* clang-format off */
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
#ifndef mlx_get_params_list
static const OSSL_PARAM mlx_get_params_list[] = {
    OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
    OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
    OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
    OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_CATEGORY, NULL),
    OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
    OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
    OSSL_PARAM_END
};
#endif

#ifndef mlx_get_params_st
struct mlx_get_params_st {
    OSSL_PARAM *bits;
    OSSL_PARAM *maxsize;
    OSSL_PARAM *priv;
    OSSL_PARAM *pub;
    OSSL_PARAM *secbits;
    OSSL_PARAM *seccat;
};
#endif

#ifndef mlx_get_params_decoder
static int mlx_get_params_decoder
    (const OSSL_PARAM *p, struct mlx_get_params_st *r)
{
    const char *s;

    memset(r, 0, sizeof(*r));
    if (p != NULL)
        for (; (s = p->key) != NULL; p++)
            switch(s[0]) {
            default:
                break;
            case 'b':
                if (ossl_likely(strcmp("its", s + 1) == 0)) {
                    /* OSSL_PKEY_PARAM_BITS */
                    if (ossl_unlikely(r->bits != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->bits = (OSSL_PARAM *)p;
                }
                break;
            case 'e':
                if (ossl_likely(strcmp("ncoded-pub-key", s + 1) == 0)) {
                    /* OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY */
                    if (ossl_unlikely(r->pub != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->pub = (OSSL_PARAM *)p;
                }
                break;
            case 'm':
                if (ossl_likely(strcmp("ax-size", s + 1) == 0)) {
                    /* OSSL_PKEY_PARAM_MAX_SIZE */
                    if (ossl_unlikely(r->maxsize != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->maxsize = (OSSL_PARAM *)p;
                }
                break;
            case 'p':
                if (ossl_likely(strcmp("riv", s + 1) == 0)) {
                    /* OSSL_PKEY_PARAM_PRIV_KEY */
                    if (ossl_unlikely(r->priv != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->priv = (OSSL_PARAM *)p;
                }
                break;
            case 's':
                switch(s[1]) {
                default:
                    break;
                case 'e':
                    switch(s[2]) {
                    default:
                        break;
                    case 'c':
                        switch(s[3]) {
                        default:
                            break;
                        case 'u':
                            switch(s[4]) {
                            default:
                                break;
                            case 'r':
                                switch(s[5]) {
                                default:
                                    break;
                                case 'i':
                                    switch(s[6]) {
                                    default:
                                        break;
                                    case 't':
                                        switch(s[7]) {
                                        default:
                                            break;
                                        case 'y':
                                            switch(s[8]) {
                                            default:
                                                break;
                                            case '-':
                                                switch(s[9]) {
                                                default:
                                                    break;
                                                case 'b':
                                                    if (ossl_likely(strcmp("its", s + 10) == 0)) {
                                                        /* OSSL_PKEY_PARAM_SECURITY_BITS */
                                                        if (ossl_unlikely(r->secbits != NULL)) {
                                                            ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                                                           "param %s is repeated", s);
                                                            return 0;
                                                        }
                                                        r->secbits = (OSSL_PARAM *)p;
                                                    }
                                                    break;
                                                case 'c':
                                                    if (ossl_likely(strcmp("ategory", s + 10) == 0)) {
                                                        /* OSSL_PKEY_PARAM_SECURITY_CATEGORY */
                                                        if (ossl_unlikely(r->seccat != NULL)) {
                                                            ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                                                           "param %s is repeated", s);
                                                            return 0;
                                                        }
                                                        r->seccat = (OSSL_PARAM *)p;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
    return 1;
}
#endif
/* End of machine generated */
/* clang-format on */

static const OSSL_PARAM *mlx_kem_gettable_params(void *provctx)
{
    return mlx_get_params_list;
}

/*
 * It is assumed the key is guaranteed non-NULL here, and is from this provider
 */
static int mlx_kem_get_params(void *vkey, OSSL_PARAM params[])
{
    MLX_KEY *key = vkey;
    OSSL_PARAM *pub, *prv = NULL;
    EXPORT_CB_ARG sub_arg;
    int selection;
    struct mlx_get_params_st p;

    if (key == NULL || !mlx_get_params_decoder(params, &p))
        return 0;

    /* The reported "bit" count is those of the ML-KEM key */
    if (p.bits != NULL)
        if (!OSSL_PARAM_set_int(p.bits, key->minfo->bits))
            return 0;

    /* The reported security bits are those of the ML-KEM key */
    if (p.secbits != NULL)
        if (!OSSL_PARAM_set_int(p.secbits, key->minfo->secbits))
            return 0;

    /* The reported security category are those of the ML-KEM key */
    if (p.seccat != NULL)
        if (!OSSL_PARAM_set_int(p.seccat, key->minfo->security_category))
            return 0;

    /* The ciphertext sizes are additive */
    if (p.maxsize != NULL)
        if (!OSSL_PARAM_set_size_t(p.maxsize, key->minfo->ctext_bytes + key->xinfo->pubkey_bytes))
            return 0;

    if (!mlx_kem_have_pubkey(key))
        return 1;

    memset(&sub_arg, 0, sizeof(sub_arg));
    if ((pub = p.pub) != NULL) {
        size_t publen = key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes;

        if (pub->data_type != OSSL_PARAM_OCTET_STRING)
            return 0;
        pub->return_size = publen;
        if (pub->data == NULL) {
            pub = NULL;
        } else if (pub->data_size < publen) {
            ERR_raise_data(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL,
                "public key output buffer too short: %lu < %lu",
                (unsigned long)pub->data_size,
                (unsigned long)publen);
            return 0;
        } else {
            sub_arg.pubenc = pub->data;
        }
    }
    if (mlx_kem_have_prvkey(key)) {
        if ((prv = p.priv) != NULL) {
            size_t prvlen = key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes;

            if (prv->data_type != OSSL_PARAM_OCTET_STRING)
                return 0;
            prv->return_size = prvlen;
            if (prv->data == NULL) {
                prv = NULL;
            } else if (prv->data_size < prvlen) {
                ERR_raise_data(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL,
                    "private key output buffer too short: %lu < %lu",
                    (unsigned long)prv->data_size,
                    (unsigned long)prvlen);
                return 0;
            } else {
                sub_arg.prvenc = prv->data;
            }
        }
    }
    if (pub == NULL && prv == NULL)
        return 1;

    selection = prv == NULL ? 0 : OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
    selection |= pub == NULL ? 0 : OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
    if (key->xinfo->group_name != NULL)
        selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;

    /* Extract sub-component key material */
    if (!export_sub(&sub_arg, selection, key)
        || (pub != NULL && sub_arg.pubcount != 2)
        || (prv != NULL && sub_arg.prvcount != 2)) {
        /* Erase any partial key material on failure */
        if (sub_arg.pubenc != NULL)
            OPENSSL_cleanse(sub_arg.pubenc,
                key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes);
        if (sub_arg.prvenc != NULL)
            OPENSSL_cleanse(sub_arg.prvenc,
                key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes);
        return 0;
    }

    return 1;
}

/* clang-format off */
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
#ifndef mlx_set_params_list
static const OSSL_PARAM mlx_set_params_list[] = {
    OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
    OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, NULL, 0),
    OSSL_PARAM_END
};
#endif

#ifndef mlx_set_params_st
struct mlx_set_params_st {
    OSSL_PARAM *propq;
    OSSL_PARAM *pub;
};
#endif

#ifndef mlx_set_params_decoder
static int mlx_set_params_decoder
    (const OSSL_PARAM *p, struct mlx_set_params_st *r)
{
    const char *s;

    memset(r, 0, sizeof(*r));
    if (p != NULL)
        for (; (s = p->key) != NULL; p++)
            switch(s[0]) {
            default:
                break;
            case 'e':
                if (ossl_likely(strcmp("ncoded-pub-key", s + 1) == 0)) {
                    /* OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY */
                    if (ossl_unlikely(r->pub != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->pub = (OSSL_PARAM *)p;
                }
                break;
            case 'p':
                if (ossl_likely(strcmp("roperties", s + 1) == 0)) {
                    /* OSSL_PKEY_PARAM_PROPERTIES */
                    if (ossl_unlikely(r->propq != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->propq = (OSSL_PARAM *)p;
                }
            }
    return 1;
}
#endif
/* End of machine generated */
/* clang-format on */

static const OSSL_PARAM *mlx_kem_settable_params(void *provctx)
{
    return mlx_set_params_list;
}

static int mlx_kem_set_params(void *vkey, const OSSL_PARAM params[])
{
    MLX_KEY *key = vkey;
    struct mlx_set_params_st p;
    const void *pubenc = NULL;
    size_t publen = 0;

    if (key == NULL || !mlx_set_params_decoder(params, &p))
        return 0;

    if (p.propq != NULL) {
        OPENSSL_free(key->propq);
        key->propq = NULL;
        if (!OSSL_PARAM_get_utf8_string(p.propq, &key->propq, 0))
            return 0;
    }

    if (p.pub == NULL)
        return 1;

    /* Key mutation is reportedly generally not allowed */
    if (mlx_kem_have_pubkey(key)) {
        ERR_raise_data(ERR_LIB_PROV,
            PROV_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE,
            "keys cannot be mutated");
        return 0;
    }
    /* An unlikely failure mode is the parameter having some unexpected type */
    if (!OSSL_PARAM_get_octet_string_ptr(p.pub, &pubenc, &publen))
        return 0;

    if (publen != key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes) {
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
        return 0;
    }

    return load_keys(key, pubenc, publen, NULL, 0);
}

/* clang-format off */
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
#ifndef mlx_gen_set_params_list
static const OSSL_PARAM mlx_gen_set_params_list[] = {
    OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, NULL, 0),
    OSSL_PARAM_END
};
#endif

#ifndef mlx_gen_set_params_st
struct mlx_gen_set_params_st {
    OSSL_PARAM *propq;
};
#endif

#ifndef mlx_gen_set_params_decoder
static int mlx_gen_set_params_decoder
    (const OSSL_PARAM *p, struct mlx_gen_set_params_st *r)
{
    const char *s;

    memset(r, 0, sizeof(*r));
    if (p != NULL)
        for (; (s = p->key) != NULL; p++)
            if (ossl_likely(strcmp("properties", s + 0) == 0)) {
                /* OSSL_PKEY_PARAM_PROPERTIES */
                if (ossl_unlikely(r->propq != NULL)) {
                    ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                   "param %s is repeated", s);
                    return 0;
                }
                r->propq = (OSSL_PARAM *)p;
            }
    return 1;
}
#endif
/* End of machine generated */
/* clang-format on */

static int mlx_kem_gen_set_params(void *vgctx, const OSSL_PARAM params[])
{
    PROV_ML_KEM_GEN_CTX *gctx = vgctx;
    struct mlx_gen_set_params_st p;

    if (gctx == NULL || !mlx_gen_set_params_decoder(params, &p))
        return 0;

    if (p.propq != NULL) {
        if (p.propq->data_type != OSSL_PARAM_UTF8_STRING)
            return 0;
        OPENSSL_free(gctx->propq);
        if ((gctx->propq = OPENSSL_strdup(p.propq->data)) == NULL)
            return 0;
    }
    return 1;
}

static void *mlx_kem_gen_init(int evp_type, OSSL_LIB_CTX *libctx,
    int selection, const OSSL_PARAM params[])
{
    PROV_ML_KEM_GEN_CTX *gctx = NULL;

    /*
     * We can only generate private keys, check that the selection is
     * appropriate.
     */
    if (!ossl_prov_is_running()
        || (selection & minimal_selection) == 0
        || (gctx = OPENSSL_zalloc(sizeof(*gctx))) == NULL)
        return NULL;

    gctx->evp_type = evp_type;
    gctx->libctx = libctx;
    gctx->selection = selection;
    if (mlx_kem_gen_set_params(gctx, params))
        return gctx;

    mlx_kem_gen_cleanup(gctx);
    return NULL;
}

static const OSSL_PARAM *mlx_kem_gen_settable_params(ossl_unused void *vgctx,
    ossl_unused void *provctx)
{
    return mlx_gen_set_params_list;
}

static void *mlx_kem_gen(void *vgctx, OSSL_CALLBACK *osslcb, void *cbarg)
{
    PROV_ML_KEM_GEN_CTX *gctx = vgctx;
    MLX_KEY *key;
    char *propq;

    if (gctx == NULL
        || (gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
        return NULL;

    /* Lose ownership of propq */
    propq = gctx->propq;
    gctx->propq = NULL;
    if ((key = mlx_kem_key_new(gctx->evp_type, gctx->libctx, propq)) == NULL)
        return NULL;

    if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
        return key;

    /* For now, using the same "propq" for all components */
    key->mkey = EVP_PKEY_Q_keygen(key->libctx, key->propq,
        key->minfo->algorithm_name);
    key->xkey = EVP_PKEY_Q_keygen(key->libctx, key->propq,
        key->xinfo->algorithm_name,
        key->xinfo->group_name);
    if (key->mkey != NULL && key->xkey != NULL) {
        key->state = MLX_HAVE_PRVKEY;
        return key;
    }

    mlx_kem_key_free(key);
    return NULL;
}

static void mlx_kem_gen_cleanup(void *vgctx)
{
    PROV_ML_KEM_GEN_CTX *gctx = vgctx;

    if (gctx == NULL)
        return;
    OPENSSL_free(gctx->propq);
    OPENSSL_free(gctx);
}

static void *mlx_kem_dup(const void *vkey, int selection)
{
    const MLX_KEY *key = vkey;
    MLX_KEY *ret;

    if (!ossl_prov_is_running()
        || (ret = OPENSSL_memdup(key, sizeof(*ret))) == NULL)
        return NULL;

    ret->mkey = ret->xkey = NULL;

    if (key->propq != NULL
        && (ret->propq = OPENSSL_strdup(key->propq)) == NULL) {
        OPENSSL_free(ret);
        return NULL;
    }

    /* Absent key material, nothing left to do */
    if (key->mkey == NULL) {
        if (key->xkey == NULL)
            return ret;
        /* Fail if the source key is an inconsistent state */
        OPENSSL_free(ret->propq);
        OPENSSL_free(ret);
        return NULL;
    }

    switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) {
    case 0:
        ret->state = MLX_HAVE_NOKEYS;
        return ret;
    case OSSL_KEYMGMT_SELECT_KEYPAIR:
        ret->mkey = EVP_PKEY_dup(key->mkey);
        ret->xkey = EVP_PKEY_dup(key->xkey);
        if (ret->xkey != NULL && ret->mkey != NULL)
            return ret;
        break;
    default:
        ERR_raise_data(ERR_LIB_PROV, PROV_R_UNSUPPORTED_SELECTION,
            "duplication of partial key material not supported");
        break;
    }

    mlx_kem_key_free(ret);
    return NULL;
}

#define DECLARE_DISPATCH(name, variant)                                                    \
    static OSSL_FUNC_keymgmt_new_fn mlx_##name##_kem_new;                                  \
    static void *mlx_##name##_kem_new(void *provctx)                                       \
    {                                                                                      \
        OSSL_LIB_CTX *libctx;                                                              \
                                                                                           \
        libctx = provctx == NULL ? NULL : PROV_LIBCTX_OF(provctx);                         \
        return mlx_kem_key_new(variant, libctx, NULL);                                     \
    }                                                                                      \
    static OSSL_FUNC_keymgmt_gen_init_fn mlx_##name##_kem_gen_init;                        \
    static void *mlx_##name##_kem_gen_init(void *provctx, int selection,                   \
        const OSSL_PARAM params[])                                                         \
    {                                                                                      \
        OSSL_LIB_CTX *libctx;                                                              \
                                                                                           \
        libctx = provctx == NULL ? NULL : PROV_LIBCTX_OF(provctx);                         \
        return mlx_kem_gen_init(variant, libctx, selection, params);                       \
    }                                                                                      \
    const OSSL_DISPATCH ossl_mlx_##name##_kem_kmgmt_functions[] = {                        \
        { OSSL_FUNC_KEYMGMT_NEW, (OSSL_FUNC)mlx_##name##_kem_new },                        \
        { OSSL_FUNC_KEYMGMT_FREE, (OSSL_FUNC)mlx_kem_key_free },                           \
        { OSSL_FUNC_KEYMGMT_GET_PARAMS, (OSSL_FUNC)mlx_kem_get_params },                   \
        { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (OSSL_FUNC)mlx_kem_gettable_params },         \
        { OSSL_FUNC_KEYMGMT_SET_PARAMS, (OSSL_FUNC)mlx_kem_set_params },                   \
        { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (OSSL_FUNC)mlx_kem_settable_params },         \
        { OSSL_FUNC_KEYMGMT_HAS, (OSSL_FUNC)mlx_kem_has },                                 \
        { OSSL_FUNC_KEYMGMT_MATCH, (OSSL_FUNC)mlx_kem_match },                             \
        { OSSL_FUNC_KEYMGMT_GEN_INIT, (OSSL_FUNC)mlx_##name##_kem_gen_init },              \
        { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (OSSL_FUNC)mlx_kem_gen_set_params },           \
        { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS, (OSSL_FUNC)mlx_kem_gen_settable_params }, \
        { OSSL_FUNC_KEYMGMT_GEN, (OSSL_FUNC)mlx_kem_gen },                                 \
        { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (OSSL_FUNC)mlx_kem_gen_cleanup },                 \
        { OSSL_FUNC_KEYMGMT_DUP, (OSSL_FUNC)mlx_kem_dup },                                 \
        { OSSL_FUNC_KEYMGMT_IMPORT, (OSSL_FUNC)mlx_kem_import },                           \
        { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (OSSL_FUNC)mlx_kem_imexport_types },             \
        { OSSL_FUNC_KEYMGMT_EXPORT, (OSSL_FUNC)mlx_kem_export },                           \
        { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (OSSL_FUNC)mlx_kem_imexport_types },             \
        OSSL_DISPATCH_END                                                                  \
    }
/* See |hybrid_vtable| above */
DECLARE_DISPATCH(p256, 0);
DECLARE_DISPATCH(p384, 1);
#if !defined(OPENSSL_NO_ECX)
DECLARE_DISPATCH(x25519, 2);
DECLARE_DISPATCH(x448, 3);
#endif
