/* $Id: ncat_ssl.c 11795 2009-01-21 22:16:20Z 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

