/* $Id: ncat_ssl.c 12720 2009-03-27 19:48:00Z david $ */

#include "nbase.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_OPENSSL
#include "nsock.h"
#include "ncat.h"

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

static SSL_CTX *sslctx;

SSL_CTX *setup_ssl_listen(void)
{
    SSL_METHOD *method;

    if (sslctx)
        goto done;

    SSL_library_init();
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
    SSL_load_error_strings();
    if (!(method = SSLv23_server_method()))
        bye("SSLv23_server_method(): %s.", ERR_error_string(ERR_get_error(), NULL));
    if (!(sslctx = SSL_CTX_new(method)))
        bye("SSL_CTX_new(): %s.", ERR_error_string(ERR_get_error(), NULL));
    if (o.sslcert && SSL_CTX_use_certificate_file(sslctx, o.sslcert, SSL_FILETYPE_PEM) != 1)
        bye("SSL_CTX_use_certificate_file(): %s.", ERR_error_string(ERR_get_error(), NULL));
    if (o.sslkey && SSL_CTX_use_PrivateKey_file(sslctx, o.sslkey, SSL_FILETYPE_PEM) != 1)
        bye("SSL_CTX_use_Privatekey_file(): %s.", ERR_error_string(ERR_get_error(), NULL));

done:
    return sslctx;
}

SSL *new_ssl(int fd)
{
    SSL *ssl;

    if (!(ssl = SSL_new(sslctx)))
        bye("SSL_new(): %s.", ERR_error_string(ERR_get_error(), NULL));
    if (!SSL_set_fd(ssl, fd))
        bye("SSL_set_fd(): %s.", ERR_error_string(ERR_get_error(), NULL));

    return ssl;
}
#endif
