#include <openssl/bn.h>
#include <assert.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/mem.h>
#include "../../internal.h"
#define BN_CTX_START_FRAMES 32
typedef struct {
size_t *indexes;
size_t depth, size;
} BN_STACK;
static void BN_STACK_init(BN_STACK *);
static void BN_STACK_cleanup(BN_STACK *);
static int BN_STACK_push(BN_STACK *, size_t idx);
static size_t BN_STACK_pop(BN_STACK *);
DEFINE_STACK_OF(BIGNUM)
struct bignum_ctx {
STACK_OF(BIGNUM) *bignums;
BN_STACK stack;
size_t used;
char error;
char defer_error;
};
BN_CTX *BN_CTX_new(void) {
BN_CTX *ret = OPENSSL_malloc(sizeof(BN_CTX));
if (!ret) {
OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->bignums = NULL;
BN_STACK_init(&ret->stack);
ret->used = 0;
ret->error = 0;
ret->defer_error = 0;
return ret;
}
void BN_CTX_free(BN_CTX *ctx) {
if (ctx == NULL) {
return;
}
assert(ctx->used == 0 || ctx->error);
sk_BIGNUM_pop_free(ctx->bignums, BN_free);
BN_STACK_cleanup(&ctx->stack);
OPENSSL_free(ctx);
}
void BN_CTX_start(BN_CTX *ctx) {
if (ctx->error) {
return;
}
if (!BN_STACK_push(&ctx->stack, ctx->used)) {
ctx->error = 1;
ctx->defer_error = 1;
}
}
BIGNUM *BN_CTX_get(BN_CTX *ctx) {
if (ctx->error) {
if (ctx->defer_error) {
OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
ctx->defer_error = 0;
}
return NULL;
}
if (ctx->bignums == NULL) {
ctx->bignums = sk_BIGNUM_new_null();
if (ctx->bignums == NULL) {
OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
ctx->error = 1;
return NULL;
}
}
if (ctx->used == sk_BIGNUM_num(ctx->bignums)) {
BIGNUM *bn = BN_new();
if (bn == NULL || !sk_BIGNUM_push(ctx->bignums, bn)) {
OPENSSL_PUT_ERROR(BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
BN_free(bn);
ctx->error = 1;
return NULL;
}
}
BIGNUM *ret = sk_BIGNUM_value(ctx->bignums, ctx->used);
BN_zero(ret);
ctx->used++;
return ret;
}
void BN_CTX_end(BN_CTX *ctx) {
if (ctx->error) {
return;
}
ctx->used = BN_STACK_pop(&ctx->stack);
}
static void BN_STACK_init(BN_STACK *st) {
st->indexes = NULL;
st->depth = st->size = 0;
}
static void BN_STACK_cleanup(BN_STACK *st) {
OPENSSL_free(st->indexes);
}
static int BN_STACK_push(BN_STACK *st, size_t idx) {
if (st->depth == st->size) {
size_t new_size = st->size != 0 ? st->size * 3 / 2 : BN_CTX_START_FRAMES;
if (new_size <= st->size || new_size > ((size_t)-1) / sizeof(size_t)) {
return 0;
}
size_t *new_indexes =
OPENSSL_realloc(st->indexes, new_size * sizeof(size_t));
if (new_indexes == NULL) {
return 0;
}
st->indexes = new_indexes;
st->size = new_size;
}
st->indexes[st->depth] = idx;
st->depth++;
return 1;
}
static size_t BN_STACK_pop(BN_STACK *st) {
assert(st->depth > 0);
st->depth--;
return st->indexes[st->depth];
}