/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * 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 "certificateverifier.h"
#include <QSslCertificate>
#include <QSslError>
#include <QtDebug>
#include <vmime/security/cert/certificateExpiredException.hpp>
#include <vmime/security/cert/certificateNotYetValidException.hpp>
#include <vmime/security/cert/serverIdentityException.hpp>
#include "vmimeconversions.h"

namespace LeechCraft
{
namespace Snails
{
	void CertificateVerifier::verify (vmime::shared_ptr<vmime::security::cert::certificateChain> chain,
			const vmime::string& host)
	{
		namespace vsc = vmime::security::cert;

		QList<QSslCertificate> qtChain;
		for (size_t i = 0; i < chain->getCount (); ++i)
		{
			const auto& item = chain->getAt (i);

			const auto& subcerts = ToSslCerts (item);
			if (subcerts.size () != 1)
			{
				qWarning () << Q_FUNC_INFO
						<< "unexpected certificates count for certificate type"
						<< item->getType ().c_str ()
						<< ", got"
						<< subcerts.size ()
						<< "certificates";
				throw vsc::unsupportedCertificateTypeException { "unexpected certificates counts" };
			}

			qtChain << subcerts.at (0);
		}

		const auto& errs = QSslCertificate::verify (qtChain, QString::fromStdString (host));
		if (errs.isEmpty ())
			return;

		qWarning () << Q_FUNC_INFO
				<< errs;

		for (const auto& error : errs)
			switch (error.error ())
			{
			case QSslError::CertificateExpired:
				throw vsc::certificateExpiredException {};
			case QSslError::CertificateNotYetValid:
				throw vsc::certificateNotYetValidException {};
			case QSslError::HostNameMismatch:
				throw vsc::serverIdentityException {};
			case QSslError::UnableToDecryptCertificateSignature:
			case QSslError::InvalidNotAfterField:
			case QSslError::InvalidNotBeforeField:
			case QSslError::CertificateSignatureFailed:
			case QSslError::PathLengthExceeded:
			case QSslError::UnspecifiedError:
				throw vsc::unsupportedCertificateTypeException { "incorrect format" };
			case QSslError::UnableToGetIssuerCertificate:
			case QSslError::UnableToGetLocalIssuerCertificate:
			case QSslError::UnableToDecodeIssuerPublicKey:
			case QSslError::UnableToVerifyFirstCertificate:
			case QSslError::SubjectIssuerMismatch:
			case QSslError::AuthorityIssuerSerialNumberMismatch:
				throw vsc::certificateIssuerVerificationException {};
			case QSslError::SelfSignedCertificate:
			case QSslError::SelfSignedCertificateInChain:
			case QSslError::CertificateRevoked:
			case QSslError::InvalidCaCertificate:
			case QSslError::InvalidPurpose:
			case QSslError::CertificateUntrusted:
			case QSslError::CertificateRejected:
			case QSslError::NoPeerCertificate:
			case QSslError::CertificateBlacklisted:
				throw vsc::certificateNotTrustedException {};
			case QSslError::NoError:
			case QSslError::NoSslSupport:
				break;
			}

		throw vsc::certificateException { "other certificate error" };
	}
}
}
