//
// SecureSocketImpl.cpp
//
// $Id: //poco/Main/NetSSL_OpenSSL/src/SecureSocketImpl.cpp#29 $
//
// Library: NetSSL_OpenSSL
// Package: SSLSockets
// Module:  SecureSocketImpl
//
// Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
// 
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//


#include "Poco/Net/SecureSocketImpl.h"
#include "Poco/Net/SSLException.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/X509Certificate.h"
#include "Poco/Net/Utility.h"
#include "Poco/Net/SecureStreamSocket.h"
#include "Poco/Net/SecureStreamSocketImpl.h"
#include "Poco/Net/StreamSocketImpl.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/DNS.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
#include <openssl/x509v3.h>
#include <openssl/err.h>


using Poco::IOException;
using Poco::TimeoutException;
using Poco::InvalidArgumentException;
using Poco::NumberFormatter;
using Poco::Timespan;


// workaround for C++-incompatible macro
#define POCO_BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,1,(void*)((n)?"a":NULL))


namespace Poco {
namespace Net {


SecureSocketImpl::SecureSocketImpl(Poco::AutoPtr<SocketImpl> pSocketImpl, Context::Ptr pContext): 
	_pSSL(0),
	_pSocket(pSocketImpl),
	_pContext(pContext)
{
	poco_check_ptr (_pSocket);
	poco_check_ptr (_pContext);
}


SecureSocketImpl::~SecureSocketImpl()
{
	close();
}

	
SocketImpl* SecureSocketImpl::acceptConnection(SocketAddress& clientAddr)
{
	poco_assert (!_pSSL);

	StreamSocket ss = _pSocket->acceptConnection(clientAddr);
	Poco::AutoPtr<SecureStreamSocketImpl> pSecureStreamSocketImpl = new SecureStreamSocketImpl(static_cast<StreamSocketImpl*>(ss.impl()), _pContext);
	pSecureStreamSocketImpl->acceptSSL();
	pSecureStreamSocketImpl->duplicate();
	return pSecureStreamSocketImpl;
}


void SecureSocketImpl::acceptSSL()
{
	poco_assert (!_pSSL);

	BIO* pBIO = BIO_new(BIO_s_socket());
	if (!pBIO) throw SSLException("Cannot create BIO object");
	BIO_set_fd(pBIO, _pSocket->sockfd(), BIO_NOCLOSE);

	_pSSL = SSL_new(_pContext->sslContext());
	if (!_pSSL)
	{
		BIO_free(pBIO);
		throw SSLException("Cannot create SSL object");
	}
	SSL_set_bio(_pSSL, pBIO, pBIO);

	try
	{
		if (_pSocket->getBlocking())
		{
			int err = SSL_accept(_pSSL);			
			if (err > 0)
			{
				std::string clientName = _pSocket->peerAddress().host().toString();
				long certErr = verifyCertificate(clientName);
				if (certErr != X509_V_OK)
				{
					std::string msg = Utility::convertCertificateError(certErr);
					throw CertificateValidationException("Unacceptable certificate from " + clientName, msg);
				}
			}
			else
			{
				handleError(err);
			}
		}
		else
		{
			SSL_set_accept_state(_pSSL);
		}
	}
	catch (...)
	{
		SSL_shutdown(_pSSL);
		SSL_free(_pSSL);
		_pSSL = 0;
		throw;
	}
}


void SecureSocketImpl::connect(const SocketAddress& address, const std::string& hostName)
{
	poco_assert (!_pSSL);

	_pSocket->connect(address);
	connectSSL(hostName);
}


void SecureSocketImpl::connect(const SocketAddress& address, const std::string& hostName, const Poco::Timespan& timeout)
{
	poco_assert (!_pSSL);

	_pSocket->connect(address, timeout);
	connectSSL(hostName);
}


void SecureSocketImpl::connectNB(const SocketAddress& address, const std::string& hostName)
{
	poco_assert (!_pSSL);

	_pSocket->connectNB(address);
	connectSSL(hostName);
}


void SecureSocketImpl::connectSSL(const std::string& hostName)
{
	poco_assert (!_pSSL);
	poco_assert (_pSocket->initialized());
	
	BIO* pBIO = BIO_new(BIO_s_socket());
	if (!pBIO) throw SSLException("Cannot create SSL BIO object");
	BIO_set_fd(pBIO, _pSocket->sockfd(), BIO_NOCLOSE);

	_pSSL = SSL_new(_pContext->sslContext());
	if (!_pSSL) 
	{
		BIO_free(pBIO);
		throw SSLException("Cannot create SSL object");
	}
	SSL_set_bio(_pSSL, pBIO, pBIO);
	
	try
	{
		if (_pSocket->getBlocking())
		{
			int ret = SSL_connect(_pSSL);
			handleError(ret);
		
			long certErr = verifyCertificate(hostName);
			if (certErr != X509_V_OK)
			{
				std::string msg = Utility::convertCertificateError(certErr);
				throw InvalidCertificateException(msg);
			}
		}
		else
		{
			SSL_set_connect_state(_pSSL);
		}
	}
	catch (...)
	{
		SSL_free(_pSSL);
		_pSSL = 0;
		throw;
	}
}


void SecureSocketImpl::bind(const SocketAddress& address, bool reuseAddress)
{
	poco_check_ptr (_pSocket);

	_pSocket->bind(address, reuseAddress);
}

	
void SecureSocketImpl::listen(int backlog)
{
	poco_check_ptr (_pSocket);

	_pSocket->listen(backlog);
}


void SecureSocketImpl::shutdown()
{
	if (_pSSL)
	{
		// if we can't get a clean SSL shutdown after 10
		// attempts, something's probably wrong with the
		// peer and we give up.
		int rc;
		int attempts = 0;
		do
		{
			rc = SSL_shutdown(_pSSL);
			++attempts;
		}
		while (rc == 0 && attempts < 10);
		if (rc < 0) handleError(rc);
		SSL_clear(_pSSL);
		SSL_free(_pSSL);
		_pSSL = 0;
	}
}


void SecureSocketImpl::close()
{
	shutdown();
	_pSocket->close();
}


int SecureSocketImpl::sendBytes(const void* buffer, int length, int flags)
{
	poco_assert (_pSocket->initialized());
	poco_check_ptr (_pSSL);

	int rc;
	do
	{
		rc = SSL_write(_pSSL, buffer, length);
	}
	while (rc <= 0 && _pSocket->lastError() == POCO_EINTR);
	if (rc <= 0) 
	{
		return handleError(rc);
	}
	return rc;
}


int SecureSocketImpl::receiveBytes(void* buffer, int length, int flags)
{
	poco_assert (_pSocket->initialized());
	poco_check_ptr (_pSSL);

	int rc;
	do
	{
		rc = SSL_read(_pSSL, buffer, length);
	}
	while (rc <= 0 && _pSocket->lastError() == POCO_EINTR);
	if (rc <= 0) 
	{
		return handleError(rc);
	}
	return rc;
}


long SecureSocketImpl::verifyCertificate(const std::string& hostName)
{
	Context::VerificationMode mode = _pContext->verificationMode();
	if (mode == Context::VERIFY_NONE || isLocalHost(hostName) && mode != Context::VERIFY_STRICT)
	{
		return X509_V_OK;
	}

	X509* pCert = SSL_get_peer_certificate(_pSSL);
	if (pCert)
	{
		X509Certificate cert(pCert);
		return cert.verify(hostName);
	}
	else return X509_V_OK;
}



bool SecureSocketImpl::isLocalHost(const std::string& hostName)
{
	SocketAddress addr(hostName, 0);
	return addr.host().isLoopback();
}


X509* SecureSocketImpl::peerCertificate() const
{
	if (_pSSL)
		return SSL_get_peer_certificate(_pSSL);
	else
		return 0;
}


int SecureSocketImpl::handleError(int rc)
{
	if (rc > 0) return rc;

	int sslError = SSL_get_error(_pSSL, rc);	
	switch (sslError)
	{
	case SSL_ERROR_ZERO_RETURN:
		return 0;
	case SSL_ERROR_WANT_READ:
		return SecureStreamSocket::ERR_SSL_WANT_READ;
	case SSL_ERROR_WANT_WRITE:
		return SecureStreamSocket::ERR_SSL_WANT_WRITE;
	case SSL_ERROR_WANT_CONNECT: 
	case SSL_ERROR_WANT_ACCEPT:
	case SSL_ERROR_WANT_X509_LOOKUP:
		// these should not occur
		poco_bugcheck();
		return rc;
	case SSL_ERROR_SYSCALL:
	case SSL_ERROR_SSL:
		{
			long lastError = ERR_get_error();
			if (lastError == 0)
			{
				if (rc == 0)
				{
					throw SSLException("The underlying socket connection has been unexpectedly closed");
				}
				else if (rc == -1)
				{
					SecureStreamSocketImpl::error("The BIO reported an error");
				}
			}
			else
			{
				char buffer[256];
				ERR_error_string_n(lastError, buffer, sizeof(buffer));
				std::string msg(buffer);
				throw SSLException(msg);
			}
		}
 		break;
	default:
		break;
	}
	return rc;
}


} } // namespace Poco::Net
