int X509_TRUST_add(int id, int flags, int (*ck) (X509_TRUST *, X509 *, int),
                   const char *name, int arg1, void *arg2)
{
    int idx;
    X509_TRUST *trtmp;
    /*
     * This is set according to what we change: application can't set it
     */
    flags &= ~X509_TRUST_DYNAMIC;
    /* This will always be set for application modified trust entries */
    flags |= X509_TRUST_DYNAMIC_NAME;
    /* Get existing entry if any */
    idx = X509_TRUST_get_by_id(id);
    /* Need a new entry */
    if (idx == -1) {
        if ((trtmp = OPENSSL_malloc(sizeof(*trtmp))) == NULL) {
            X509err(X509_F_X509_TRUST_ADD, ERR_R_MALLOC_FAILURE);
            return 0;
        }
        trtmp->flags = X509_TRUST_DYNAMIC;
    } else
        trtmp = X509_TRUST_get0(idx);

    /* OPENSSL_free existing name if dynamic */
    if (trtmp->flags & X509_TRUST_DYNAMIC_NAME)
        OPENSSL_free(trtmp->name);
    /* dup supplied name */
    if ((trtmp->name = OPENSSL_strdup(name)) == NULL) {
        X509err(X509_F_X509_TRUST_ADD, ERR_R_MALLOC_FAILURE);
        goto err;
    }
    /* Keep the dynamic flag of existing entry */
    trtmp->flags &= X509_TRUST_DYNAMIC;
    /* Set all other flags */
    trtmp->flags |= flags;

    trtmp->trust = id;
    trtmp->check_trust = ck;
    trtmp->arg1 = arg1;
    trtmp->arg2 = arg2;

    /* If its a new entry manage the dynamic table */
    if (idx == -1) {
        if (trtable == NULL
            && (trtable = sk_X509_TRUST_new(tr_cmp)) == NULL) {
            X509err(X509_F_X509_TRUST_ADD, ERR_R_MALLOC_FAILURE);
            goto err;;
        }
        if (!sk_X509_TRUST_push(trtable, trtmp)) {
            X509err(X509_F_X509_TRUST_ADD, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }
    return 1;
 err:
    if (idx == -1) {
        OPENSSL_free(trtmp->name);
        OPENSSL_free(trtmp);
    }
    return 0;
}