/*
 * Copyright 2019-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 */

/* Dispatch functions for chacha20_poly1305 cipher */

#include <string.h>
#include <openssl/proverr.h>
#include "cipher_chacha20_poly1305.h"
#include "prov/implementations.h"
#include "prov/providercommon.h"

#define CHACHA20_POLY1305_KEYLEN CHACHA_KEY_SIZE
#define CHACHA20_POLY1305_BLKLEN 1
#define CHACHA20_POLY1305_MAX_IVLEN 12
#define CHACHA20_POLY1305_MODE 0
#define CHACHA20_POLY1305_FLAGS (PROV_CIPHER_FLAG_AEAD \
    | PROV_CIPHER_FLAG_CUSTOM_IV)

static OSSL_FUNC_cipher_newctx_fn chacha20_poly1305_newctx;
static OSSL_FUNC_cipher_freectx_fn chacha20_poly1305_freectx;
static OSSL_FUNC_cipher_dupctx_fn chacha20_poly1305_dupctx;
static OSSL_FUNC_cipher_encrypt_init_fn chacha20_poly1305_einit;
static OSSL_FUNC_cipher_decrypt_init_fn chacha20_poly1305_dinit;
static OSSL_FUNC_cipher_get_params_fn chacha20_poly1305_get_params;
static OSSL_FUNC_cipher_get_ctx_params_fn chacha20_poly1305_get_ctx_params;
static OSSL_FUNC_cipher_set_ctx_params_fn chacha20_poly1305_set_ctx_params;
static OSSL_FUNC_cipher_cipher_fn chacha20_poly1305_cipher;
static OSSL_FUNC_cipher_update_fn chacha20_poly1305_update;
static OSSL_FUNC_cipher_final_fn chacha20_poly1305_final;
static OSSL_FUNC_cipher_gettable_ctx_params_fn chacha20_poly1305_gettable_ctx_params;
static OSSL_FUNC_cipher_settable_ctx_params_fn chacha20_poly1305_settable_ctx_params;
#define chacha20_poly1305_gettable_params ossl_cipher_generic_gettable_params

static void *chacha20_poly1305_newctx(void *provctx)
{
    PROV_CHACHA20_POLY1305_CTX *ctx;

    if (!ossl_prov_is_running())
        return NULL;

    ctx = OPENSSL_zalloc(sizeof(*ctx));
    if (ctx != NULL) {
        ossl_cipher_generic_initkey(&ctx->base, CHACHA20_POLY1305_KEYLEN * 8,
            CHACHA20_POLY1305_BLKLEN * 8,
            CHACHA20_POLY1305_IVLEN * 8,
            CHACHA20_POLY1305_MODE,
            CHACHA20_POLY1305_FLAGS,
            ossl_prov_cipher_hw_chacha20_poly1305(
                CHACHA20_POLY1305_KEYLEN * 8),
            NULL);
        ctx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH;
        ossl_chacha20_initctx(&ctx->chacha);
    }
    return ctx;
}

static void *chacha20_poly1305_dupctx(void *provctx)
{
    PROV_CHACHA20_POLY1305_CTX *ctx = provctx;
    PROV_CHACHA20_POLY1305_CTX *dctx = NULL;

    if (ctx == NULL)
        return NULL;
    dctx = OPENSSL_memdup(ctx, sizeof(*ctx));
    if (dctx != NULL && dctx->base.tlsmac != NULL && dctx->base.alloced) {
        dctx->base.tlsmac = OPENSSL_memdup(dctx->base.tlsmac,
            dctx->base.tlsmacsize);
        if (dctx->base.tlsmac == NULL) {
            OPENSSL_free(dctx);
            dctx = NULL;
        }
    }
    return dctx;
}

static void chacha20_poly1305_freectx(void *vctx)
{
    PROV_CHACHA20_POLY1305_CTX *ctx = (PROV_CHACHA20_POLY1305_CTX *)vctx;

    if (ctx != NULL) {
        ossl_cipher_generic_reset_ctx((PROV_CIPHER_CTX *)vctx);
        OPENSSL_clear_free(ctx, sizeof(*ctx));
    }
}

static int chacha20_poly1305_get_params(OSSL_PARAM params[])
{
    return ossl_cipher_generic_get_params(params, 0, CHACHA20_POLY1305_FLAGS,
        CHACHA20_POLY1305_KEYLEN * 8,
        CHACHA20_POLY1305_BLKLEN * 8,
        CHACHA20_POLY1305_IVLEN * 8);
}

/* clang-format off */
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
#ifndef chacha20_poly1305_get_ctx_params_list
static const OSSL_PARAM chacha20_poly1305_get_ctx_params_list[] = {
    OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_KEYLEN, NULL),
    OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_IVLEN, NULL),
    OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_AEAD_TAGLEN, NULL),
    OSSL_PARAM_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG, NULL, 0),
    OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD, NULL),
    OSSL_PARAM_END
};
#endif

#ifndef chacha20_poly1305_get_ctx_params_st
struct chacha20_poly1305_get_ctx_params_st {
    OSSL_PARAM *ivlen;
    OSSL_PARAM *keylen;
    OSSL_PARAM *pad;
    OSSL_PARAM *tag;
    OSSL_PARAM *taglen;
};
#endif

#ifndef chacha20_poly1305_get_ctx_params_decoder
static int chacha20_poly1305_get_ctx_params_decoder
    (const OSSL_PARAM *p, struct chacha20_poly1305_get_ctx_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 'i':
                if (ossl_likely(strcmp("vlen", s + 1) == 0)) {
                    /* OSSL_CIPHER_PARAM_IVLEN */
                    if (ossl_unlikely(r->ivlen != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->ivlen = (OSSL_PARAM *)p;
                }
                break;
            case 'k':
                if (ossl_likely(strcmp("eylen", s + 1) == 0)) {
                    /* OSSL_CIPHER_PARAM_KEYLEN */
                    if (ossl_unlikely(r->keylen != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->keylen = (OSSL_PARAM *)p;
                }
                break;
            case 't':
                switch(s[1]) {
                default:
                    break;
                case 'a':
                    switch(s[2]) {
                    default:
                        break;
                    case 'g':
                        switch(s[3]) {
                        default:
                            break;
                        case 'l':
                            if (ossl_likely(strcmp("en", s + 4) == 0)) {
                                /* OSSL_CIPHER_PARAM_AEAD_TAGLEN */
                                if (ossl_unlikely(r->taglen != NULL)) {
                                    ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                                   "param %s is repeated", s);
                                    return 0;
                                }
                                r->taglen = (OSSL_PARAM *)p;
                            }
                            break;
                        case '\0':
                            if (ossl_unlikely(r->tag != NULL)) {
                                ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                               "param %s is repeated", s);
                                return 0;
                            }
                            r->tag = (OSSL_PARAM *)p;
                        }
                    }
                    break;
                case 'l':
                    if (ossl_likely(strcmp("saadpad", s + 2) == 0)) {
                        /* OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD */
                        if (ossl_unlikely(r->pad != NULL)) {
                            ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                           "param %s is repeated", s);
                            return 0;
                        }
                        r->pad = (OSSL_PARAM *)p;
                    }
                }
            }
    return 1;
}
#endif
/* End of machine generated */
/* clang-format on */

static int chacha20_poly1305_get_ctx_params(void *vctx, OSSL_PARAM params[])
{
    PROV_CHACHA20_POLY1305_CTX *ctx = (PROV_CHACHA20_POLY1305_CTX *)vctx;
    struct chacha20_poly1305_get_ctx_params_st p;

    if (ctx == NULL || !chacha20_poly1305_get_ctx_params_decoder(params, &p))
        return 0;

    if (p.ivlen != NULL
        && !OSSL_PARAM_set_size_t(p.ivlen, CHACHA20_POLY1305_IVLEN)) {
        ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
        return 0;
    }

    if (p.keylen != NULL
        && !OSSL_PARAM_set_size_t(p.keylen, CHACHA20_POLY1305_KEYLEN)) {
        ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
        return 0;
    }

    if (p.taglen != NULL
        && !OSSL_PARAM_set_size_t(p.taglen, ctx->tag_len)) {
        ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
        return 0;
    }

    if (p.pad != NULL
        && !OSSL_PARAM_set_size_t(p.pad, ctx->tls_aad_pad_sz)) {
        ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
        return 0;
    }

    if (p.tag != NULL) {
        if (p.tag->data_type != OSSL_PARAM_OCTET_STRING) {
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
            return 0;
        }
        if (!ctx->base.enc) {
            ERR_raise(ERR_LIB_PROV, PROV_R_TAG_NOT_SET);
            return 0;
        }
        if (p.tag->data_size == 0 || p.tag->data_size > POLY1305_BLOCK_SIZE) {
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_TAG_LENGTH);
            return 0;
        }
        memcpy(p.tag->data, ctx->tag, p.tag->data_size);
    }
    return 1;
}

static const OSSL_PARAM *chacha20_poly1305_gettable_ctx_params(ossl_unused void *cctx, ossl_unused void *provctx)
{
    return chacha20_poly1305_get_ctx_params_list;
}

/* clang-format off */
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
#ifndef chacha20_poly1305_set_ctx_params_list
static const OSSL_PARAM chacha20_poly1305_set_ctx_params_list[] = {
    OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_KEYLEN, NULL),
    OSSL_PARAM_size_t(OSSL_CIPHER_PARAM_IVLEN, NULL),
    OSSL_PARAM_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG, NULL, 0),
    OSSL_PARAM_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD, NULL, 0),
    OSSL_PARAM_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED, NULL, 0),
    OSSL_PARAM_END
};
#endif

#ifndef chacha20_poly1305_set_ctx_params_st
struct chacha20_poly1305_set_ctx_params_st {
    OSSL_PARAM *aad;
    OSSL_PARAM *fixed;
    OSSL_PARAM *ivlen;
    OSSL_PARAM *keylen;
    OSSL_PARAM *tag;
};
#endif

#ifndef chacha20_poly1305_set_ctx_params_decoder
static int chacha20_poly1305_set_ctx_params_decoder
    (const OSSL_PARAM *p, struct chacha20_poly1305_set_ctx_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 'i':
                if (ossl_likely(strcmp("vlen", s + 1) == 0)) {
                    /* OSSL_CIPHER_PARAM_IVLEN */
                    if (ossl_unlikely(r->ivlen != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->ivlen = (OSSL_PARAM *)p;
                }
                break;
            case 'k':
                if (ossl_likely(strcmp("eylen", s + 1) == 0)) {
                    /* OSSL_CIPHER_PARAM_KEYLEN */
                    if (ossl_unlikely(r->keylen != NULL)) {
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                       "param %s is repeated", s);
                        return 0;
                    }
                    r->keylen = (OSSL_PARAM *)p;
                }
                break;
            case 't':
                switch(s[1]) {
                default:
                    break;
                case 'a':
                    if (ossl_likely(strcmp("g", s + 2) == 0)) {
                        /* OSSL_CIPHER_PARAM_AEAD_TAG */
                        if (ossl_unlikely(r->tag != NULL)) {
                            ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                           "param %s is repeated", s);
                            return 0;
                        }
                        r->tag = (OSSL_PARAM *)p;
                    }
                    break;
                case 'l':
                    switch(s[2]) {
                    default:
                        break;
                    case 's':
                        switch(s[3]) {
                        default:
                            break;
                        case 'a':
                            if (ossl_likely(strcmp("ad", s + 4) == 0)) {
                                /* OSSL_CIPHER_PARAM_AEAD_TLS1_AAD */
                                if (ossl_unlikely(r->aad != NULL)) {
                                    ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                                   "param %s is repeated", s);
                                    return 0;
                                }
                                r->aad = (OSSL_PARAM *)p;
                            }
                            break;
                        case 'i':
                            if (ossl_likely(strcmp("vfixed", s + 4) == 0)) {
                                /* OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED */
                                if (ossl_unlikely(r->fixed != NULL)) {
                                    ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
                                                   "param %s is repeated", s);
                                    return 0;
                                }
                                r->fixed = (OSSL_PARAM *)p;
                            }
                        }
                    }
                }
            }
    return 1;
}
#endif
/* End of machine generated */
/* clang-format on */

static const OSSL_PARAM *chacha20_poly1305_settable_ctx_params(
    ossl_unused void *cctx, ossl_unused void *provctx)
{
    return chacha20_poly1305_set_ctx_params_list;
}

static int chacha20_poly1305_set_ctx_params(void *vctx,
    const OSSL_PARAM params[])
{
    size_t len;
    PROV_CHACHA20_POLY1305_CTX *ctx = (PROV_CHACHA20_POLY1305_CTX *)vctx;
    PROV_CIPHER_HW_CHACHA20_POLY1305 *hw = (PROV_CIPHER_HW_CHACHA20_POLY1305 *)ctx->base.hw;
    struct chacha20_poly1305_set_ctx_params_st p;

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

    if (p.keylen != NULL) {
        if (!OSSL_PARAM_get_size_t(p.keylen, &len)) {
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
        if (len != CHACHA20_POLY1305_KEYLEN) {
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
            return 0;
        }
    }

    if (p.ivlen != NULL) {
        if (!OSSL_PARAM_get_size_t(p.ivlen, &len)) {
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
        if (len != CHACHA20_POLY1305_MAX_IVLEN) {
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_IV_LENGTH);
            return 0;
        }
    }

    if (p.tag != NULL) {
        if (p.tag->data_type != OSSL_PARAM_OCTET_STRING) {
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
        if (p.tag->data_size == 0 || p.tag->data_size > POLY1305_BLOCK_SIZE) {
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_TAG_LENGTH);
            return 0;
        }
        if (p.tag->data != NULL) {
            if (ctx->base.enc) {
                ERR_raise(ERR_LIB_PROV, PROV_R_TAG_NOT_NEEDED);
                return 0;
            }
            memcpy(ctx->tag, p.tag->data, p.tag->data_size);
        }
        ctx->tag_len = p.tag->data_size;
    }

    if (p.aad != NULL) {
        if (p.aad->data_type != OSSL_PARAM_OCTET_STRING) {
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
        len = hw->tls_init(&ctx->base, p.aad->data, p.aad->data_size);
        if (len == 0) {
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DATA);
            return 0;
        }
        ctx->tls_aad_pad_sz = len;
    }

    if (p.fixed != NULL) {
        if (p.fixed->data_type != OSSL_PARAM_OCTET_STRING) {
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
            return 0;
        }
        if (hw->tls_iv_set_fixed(&ctx->base, p.fixed->data,
                p.fixed->data_size)
            == 0) {
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_IV_LENGTH);
            return 0;
        }
    }
    return 1;
}

static int chacha20_poly1305_einit(void *vctx, const unsigned char *key,
    size_t keylen, const unsigned char *iv,
    size_t ivlen, const OSSL_PARAM params[])
{
    int ret;

    /* The generic function checks for ossl_prov_is_running() */
    ret = ossl_cipher_generic_einit(vctx, key, keylen, iv, ivlen, NULL);
    if (ret && iv != NULL) {
        PROV_CIPHER_CTX *ctx = (PROV_CIPHER_CTX *)vctx;
        PROV_CIPHER_HW_CHACHA20_POLY1305 *hw = (PROV_CIPHER_HW_CHACHA20_POLY1305 *)ctx->hw;

        hw->initiv(ctx);
    }
    if (ret && !chacha20_poly1305_set_ctx_params(vctx, params))
        ret = 0;
    return ret;
}

static int chacha20_poly1305_dinit(void *vctx, const unsigned char *key,
    size_t keylen, const unsigned char *iv,
    size_t ivlen, const OSSL_PARAM params[])
{
    int ret;

    /* The generic function checks for ossl_prov_is_running() */
    ret = ossl_cipher_generic_dinit(vctx, key, keylen, iv, ivlen, NULL);
    if (ret && iv != NULL) {
        PROV_CIPHER_CTX *ctx = (PROV_CIPHER_CTX *)vctx;
        PROV_CIPHER_HW_CHACHA20_POLY1305 *hw = (PROV_CIPHER_HW_CHACHA20_POLY1305 *)ctx->hw;

        hw->initiv(ctx);
    }
    if (ret && !chacha20_poly1305_set_ctx_params(vctx, params))
        ret = 0;
    return ret;
}

static int chacha20_poly1305_cipher(void *vctx, unsigned char *out,
    size_t *outl, size_t outsize,
    const unsigned char *in, size_t inl)
{
    PROV_CIPHER_CTX *ctx = (PROV_CIPHER_CTX *)vctx;
    PROV_CIPHER_HW_CHACHA20_POLY1305 *hw = (PROV_CIPHER_HW_CHACHA20_POLY1305 *)ctx->hw;

    if (!ossl_prov_is_running())
        return 0;

    if (outsize < inl) {
        ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL);
        return 0;
    }

    if (!hw->aead_cipher(ctx, out, outl, in, inl))
        return 0;

    return 1;
}

static int chacha20_poly1305_update(void *vctx, unsigned char *out,
    size_t *outl, size_t outsize,
    const unsigned char *in, size_t inl)
{
    /*
     * A zero-length update is a no-op. Only EVP_Cipher() and Final produce or
     * check the authentication tag.
     */
    if (inl == 0) {
        if (!ossl_prov_is_running())
            return 0;
        *outl = 0;
        return 1;
    }

    return chacha20_poly1305_cipher(vctx, out, outl, outsize, in, inl);
}

static int chacha20_poly1305_final(void *vctx, unsigned char *out, size_t *outl,
    size_t outsize)
{
    PROV_CIPHER_CTX *ctx = (PROV_CIPHER_CTX *)vctx;
    PROV_CIPHER_HW_CHACHA20_POLY1305 *hw = (PROV_CIPHER_HW_CHACHA20_POLY1305 *)ctx->hw;

    if (!ossl_prov_is_running())
        return 0;

    if (hw->aead_cipher(ctx, out, outl, NULL, 0) <= 0)
        return 0;

    *outl = 0;
    return 1;
}

/* ossl_chacha20_ossl_poly1305_functions */
const OSSL_DISPATCH ossl_chacha20_ossl_poly1305_functions[] = {
    { OSSL_FUNC_CIPHER_NEWCTX, (void (*)(void))chacha20_poly1305_newctx },
    { OSSL_FUNC_CIPHER_FREECTX, (void (*)(void))chacha20_poly1305_freectx },
    { OSSL_FUNC_CIPHER_DUPCTX, (void (*)(void))chacha20_poly1305_dupctx },
    { OSSL_FUNC_CIPHER_ENCRYPT_INIT, (void (*)(void))chacha20_poly1305_einit },
    { OSSL_FUNC_CIPHER_DECRYPT_INIT, (void (*)(void))chacha20_poly1305_dinit },
    { OSSL_FUNC_CIPHER_UPDATE, (void (*)(void))chacha20_poly1305_update },
    { OSSL_FUNC_CIPHER_FINAL, (void (*)(void))chacha20_poly1305_final },
    { OSSL_FUNC_CIPHER_CIPHER, (void (*)(void))chacha20_poly1305_cipher },
    { OSSL_FUNC_CIPHER_GET_PARAMS,
        (void (*)(void))chacha20_poly1305_get_params },
    { OSSL_FUNC_CIPHER_GETTABLE_PARAMS,
        (void (*)(void))chacha20_poly1305_gettable_params },
    { OSSL_FUNC_CIPHER_GET_CTX_PARAMS,
        (void (*)(void))chacha20_poly1305_get_ctx_params },
    { OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS,
        (void (*)(void))chacha20_poly1305_gettable_ctx_params },
    { OSSL_FUNC_CIPHER_SET_CTX_PARAMS,
        (void (*)(void))chacha20_poly1305_set_ctx_params },
    { OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS,
        (void (*)(void))chacha20_poly1305_settable_ctx_params },
    OSSL_DISPATCH_END
};
