size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
                        unsigned char **pout,
                        int entropy, size_t min_len, size_t max_len)
{
    size_t ret = 0;
    size_t entropy_available = 0;
    RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len);

    if (pool == NULL)
        return 0;

    if (drbg->pool) {
        RAND_POOL_add(pool,
                      RAND_POOL_buffer(drbg->pool),
                      RAND_POOL_length(drbg->pool),
                      RAND_POOL_entropy(drbg->pool));
        RAND_POOL_free(drbg->pool);
        drbg->pool = NULL;
    }

    if (drbg->parent) {
        size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8);
        unsigned char *buffer = RAND_POOL_add_begin(pool, bytes_needed);

        if (buffer != NULL) {
            size_t bytes = 0;

            /* Get entropy from parent, include our state as additional input */
            if (RAND_DRBG_generate(drbg->parent,
                                   buffer, bytes_needed,
                                   0,
                                   (unsigned char *)drbg, sizeof(*drbg)) != 0)
                bytes = bytes_needed;

            entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
        }

    } else {
        /* Get entropy by polling system entropy sources. */
        entropy_available = RAND_POOL_acquire_entropy(pool);
    }

    if (entropy_available > 0) {
        ret   = RAND_POOL_length(pool);
        *pout = RAND_POOL_detach(pool);
    }

    RAND_POOL_free(pool);
    return ret;
}