/*
 * The Cryptonit security software suite is developped by IDEALX
 * Cryptonit Team (http://IDEALX.org/ and http://cryptonit.org).
 *
 * Copyright 2003-2006 IDEALX
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version
 * 2 as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301, USA. 
 *
 * In addition, as two special exceptions:
 *
 * 1) IDEALX S.A.S gives permission to:
 *  * link the code of portions of his program with the OpenSSL library under
 *    certain conditions described in each source file
 *  * distribute linked combinations including the two, with respect to the
 *    OpenSSL license and with the GPL
 *
 * You must obey the GNU General Public License in all respects for all of the
 * code used other than OpenSSL. If you modify file(s) with this exception,
 * you may extend this exception to your version of the file(s), but you are
 * not obligated to do so. If you do not wish to do so, delete this exception
 * statement from your version, in all files (this very one along with all
 * source files).
#include "P11Slot.hh" 
 * 2) IDEALX S.A.S acknowledges that portions of his sourcecode uses (by the
 * way of headers inclusion) some work published by 'RSA Security Inc.'. Those
 * portions are "derived from the RSA Security Inc. PKCS #11Cryptographic
 * Token Interface (Cryptoki)" as described in each individual source file.
 */
#include "Certificate.hh"
#include "P11Key.hh"
#include "pkcs8.hh"

#define HAVE_OPENSSL

#include "pkcs11_util.h"
#include "pkcs11_find.h"
#include "pkcs11_pkey.h"


extern "C" {
CK_RV pkcs11_list_keys (CK_FUNCTION_LIST_PTR funcs,
			    CK_SESSION_HANDLE    h_session,
			    CK_OBJECT_HANDLE_PTR *h_keys,
			    X509                 ***x509,
			    CK_ULONG_PTR         count);
CK_RV pkcs11_list_certificates(CK_FUNCTION_LIST_PTR funcs,
		CK_SESSION_HANDLE    h_session,
		CK_OBJECT_HANDLE_PTR *tab_hCerts,
		X509                 ***x509,
		CK_ULONG_PTR         count);
};


namespace Cryptonit 
{

P11Slot::P11Slot(CK_FUNCTION_LIST_PTR f,
		     CK_SLOT_ID s,
		P11Error * em,
		     PasswordManager *m) :
	err(em),
	pm(m),
	funcs(f),
	slotId(s)
{
#ifdef DEBUG
 	std::cout << "Initializing PKCS#11 slot "<< slotId << std::endl;
#endif 
	session = new P11Session(err, pm, funcs, slotId);
#ifdef DEBUG
 	std::cout << "PKCS#11 slot " << slotId << " initialized." << std::endl;
#endif 
}
    

P11Slot::~P11Slot()
{
#ifdef DEBUG
 	std::cout << "Closing PKCS#11 slot... " << slotId << std::endl;
#endif 
	//std::vector< std::pair<Certificate, CK_OBJECT_HANDLE> >::iterator i;
	/*for( i = cache.begin() ; i != cache.end() ; i++ )
	{
		cache.erase(i);
	}*/
	cache.clear();
	delete session;
#ifdef DEBUG
 	std::cout << "PKCS#11 slot " << slotId << " closed." << std::endl;
#endif 
}

CK_SLOT_INFO P11Slot::slotInfo()
{
	CK_RV rv;
	CK_SLOT_INFO slotInfo;
	rv = funcs->C_GetSlotInfo(slotId, &slotInfo);
	if(rv != CKR_OK) err->checkRV(rv);
	return slotInfo;
}
    
CK_TOKEN_INFO P11Slot::tokenInfo()
{
	CK_RV rv;
	CK_TOKEN_INFO tokenInfo;
	rv = funcs->C_GetTokenInfo(slotId, &tokenInfo);
	if(rv != CKR_OK) err->checkRV(rv);
	return tokenInfo;
}

std::vector<Certificate> P11Slot::listCertificates()
{
	std::vector<Certificate> ret = std::vector<Certificate>(0);
	CK_OBJECT_HANDLE_PTR h_certs;
	X509                 **x509;
	CK_ULONG             count;

#ifdef DEBUG
 	std::cout <<  "Fetching certificates from session " << session->handle() << "...";
#endif 

	if( session->handle() == CK_INVALID_HANDLE ) 
	{
		err->newMessage(P11Error::P11E_ERROR, "Trying to list certificates from an invalid session.", "");
	    return ret;
	}

	CK_RV rv = pkcs11_list_certificates(funcs, session->handle(), &h_certs, &x509, &count);
	if(rv == CKR_OK)
	{
#ifdef DEBUG
 		std::cout << " " << count << " certificate(s)" << std::endl;
#endif 
		for(CK_ULONG i = 0; i < count; i++) 
		{
			if( x509[i] != NULL )
			{
		    Certificate c;
		    c.setX509Certificate(x509[i]);
		    std::pair<Certificate , CK_OBJECT_HANDLE> pair;
		    pair.first = c;
				pair.second = h_certs[i]; // will be filled the first time the key is needed.
		    cache.push_back( pair );
		    ret.push_back( c );
				free(x509[i]);
		}
	    }
	}
	else
    {
		err->checkRV(rv);
		err->newMessage(P11Error::P11E_ERROR, "Cannot list certificates");
	    }
	if(x509) free(x509);
	   
	return ret;
}
	    

GetKeyReturn P11Slot::getKey(Certificate c, Key **k)
{
	CK_RV rv;
	std::vector< std::pair< Certificate, CK_OBJECT_HANDLE > >::iterator i;
	std::string hash = c.getHash();
    
	bool certfound = false;
	listCertificates(); // fill the pair "cache"
	// search the list for the given certificate
	i = cache.begin();
	while( (certfound == false) && (i != cache.end()) )
    {
		if( i->first.getHash() == hash )
    {
			certfound = true;
	}
		else i++;
    }

	// If the certificate is found , login and get the key
	if(certfound == true)
	{
		if(session->logged() == false) session->login(CKU_USER);
		if(session->logged() == true)
		{
			CK_OBJECT_HANDLE hcertif = i->second;
			CK_OBJECT_HANDLE hkey;
			CK_ULONG found = 0;
#ifdef DEBUG
 			std::cerr <<  "Looking for matching key" << std::endl;
#endif 
			rv = pkcs11_find_matching(funcs,
					session->handle(),
					hcertif,
					CKO_PRIVATE_KEY,
					CKA_ID,
					&hkey,
					&found);
			if(rv == CKR_OK && found > 0)
    {
#ifdef DEBUG
 			std::cerr <<  "Found!!" << std::endl;
#endif 
    
				EVP_PKEY *pkey = pkcs11_get_pkey(funcs, session->handle(), hkey, c.getX509Certificate());
				*k = new pkcs8(pkey);
				return gkrSUCCESS;
	} else {
#ifdef DEBUG
 			  std::cerr <<  "Not found " << std::endl;
#endif 

			  return gkrINVALID;

	}
    }
		else return gkrCANCELED;
    }
	// the certificate was not found in this slot
	return gkrINVALID;
}

bool P11Slot::hasToken()
{
	CK_RV rv;
	CK_TOKEN_INFO tokenInfo;
	if( (rv = funcs->C_GetTokenInfo(slotId, &tokenInfo) == CKR_OK) )
	    return true;
	else
	{
		err->checkRV(rv);
	    return false;
    }
}

} // namespace Cryptonit
