/* ***************************************************************** *
 * Copyright 1998 International Business Machines Corporation. All   *
 * Rights Reserved.                                                  *
 *                                                                   *
 * Please read this carefully.  Your use of this reference           *
 * implementation of certain of the IETF public-key infrastructure   *
 * specifications ("Software") indicates your acceptance of the      *
 * following.  If you do not agree to the following, do not install  *
 * or use any of the Software.                                       *
 *                                                                   *
 * Permission to use, reproduce, distribute and create derivative    *
 * works from the Software ("Software Derivative Works"), and to     *
 * distribute such Software Derivative Works is hereby granted to    *
 * you by International Business Machines Corporation ("IBM").  This *
 * permission includes a license under the patents of IBM that are   *
 * necessarily infringed by your use of the Software as provided by  *
 * IBM.                                                              *
 *                                                                   *
 * IBM licenses the Software to you on an "AS IS" basis, without     *
 * warranty of any kind.  IBM HEREBY EXPRESSLY DISCLAIMS ALL         *
 * WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING,   *
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF       *
 * MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR    *
 * PURPOSE.  You are solely responsible for determining the          *
 * appropriateness of using this Software and assume all risks       *
 * associated with the use of this Software, including but not       *
 * limited to the risks of program errors, damage to or loss of      *
 * data, programs or equipment, and unavailability or interruption   *
 * of operations.                                                    *
 *                                                                   *
 * IBM WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, *
 * INCIDENTAL, OR  INDIRECT DAMAGES OR FOR ANY ECONOMIC              *
 * CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN   *
 * IF IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  IBM  *
 * will not be liable for the loss of, or damage to, your records or *
 * data, or any damages claimed by you based on a third party claim. *
 *                                                                   *
 * IBM wishes to obtain your feedback to assist in improving the     *
 * Software.  You grant IBM a world-wide, royalty-free right to use, *
 * copy, distribute, sublicense and prepare derivative works based   *
 * upon any feedback, including materials, error corrections,        *
 * Software Derivatives, enhancements, suggestions and the like that *
 * you provide to IBM relating to the Software (this does not        *
 * include products for which you charge a royalty and distribute to *
 * IBM under other terms and conditions).                            *
 *                                                                   *
 * You agree to distribute the Software and any Software Derivatives *
 * under a license agreement that: 1) is sufficient to notify all    *
 * licensees of the Software and Software Derivatives that IBM       *
 * assumes no liability for any claim that may arise regarding the   *
 * Software or Software Derivatives, and 2) that disclaims all       *
 * warranties, both express and implied, from IBM regarding the      *
 * Software and Software Derivatives.  (If you include this          *
 * Agreement with any distribution of the Software or Software       *
 * Derivatives you will have met this requirement.)  You agree that  *
 * you will not delete any copyright notices in the Software.        *
 *                                                                   *
 * This Agreement is the exclusive statement of your rights in the   *
 * Software as provided by IBM.   Except for the rights granted to   *
 * you in the second paragraph above, You are not granted any other  *
 * patent rights, including but not limited to the right to make     *
 * combinations of the Software with products that infringe IBM      *
 * patents. You agree to comply with all applicable laws and         *
 * regulations, including all export and import laws and regulation. *
 * This Agreement is governed by the laws of the State of New York.  *
 * This Agreement supersedes all other communications,               *
 * understandings or agreements we may have had prior to this        *
 * Agreement.                                                        *
 * ***************************************************************** */

#include "ibmcylinkcsp.hpp"
#include "session.hpp"
#include "csp.hpp"
#include "cssmspi.h"
#include "cspspi.hpp"
#include "exception.hpp"
#include "cssmerr.h"

/**********************************************************
 *
 *	CSP class
 *
 **********************************************************/
CSP::CSP() {
	head = NULL;

	CSSM_GUID				guid = IBMCYLINKCSP_GUID; // our GUID
	CSSM_SPI_CSP_FUNCS		cspFuncTable;
	CSSM_REGISTRATION_INFO	regInfo;
	CSSM_MODULE_FUNCS		services[1];

	// Set up function table
	cspFuncTable.DecryptData		= DecryptData;
	cspFuncTable.DecryptDataInit	= DecryptDataInit;
	cspFuncTable.DecryptDataUpdate	= DecryptDataUpdate;
	cspFuncTable.DecryptDataFinal	= DecryptDataFinal;

	cspFuncTable.DigestData			= DigestData;
	cspFuncTable.DigestDataInit		= DigestDataInit;
	cspFuncTable.DigestDataUpdate	= DigestDataUpdate;
	cspFuncTable.DigestDataFinal	= DigestDataFinal;
	cspFuncTable.DigestDataClone	= NULL;

	cspFuncTable.EncryptData		= EncryptData;
	cspFuncTable.EncryptDataInit	= EncryptDataInit;
	cspFuncTable.EncryptDataUpdate	= EncryptDataUpdate;
	cspFuncTable.EncryptDataFinal	= EncryptDataFinal;

	cspFuncTable.GenerateKey		= GenerateKey;
	cspFuncTable.GenerateKeyPair	= GenerateKeyPair;

	cspFuncTable.GenerateMac		= NULL;
	cspFuncTable.GenerateMacInit	= NULL;
	cspFuncTable.GenerateMacUpdate	= NULL;
	cspFuncTable.GenerateMacFinal	= NULL;

	cspFuncTable.GenerateRandom		= GenerateRandom;

	cspFuncTable.PassThrough		= NULL;

	cspFuncTable.QuerySize			= NULL; //???
	cspFuncTable.QueryKeySizeInBits	= QueryKeySizeInBits;

	cspFuncTable.SignData			= SignData;
	cspFuncTable.SignDataInit		= SignDataInit;
	cspFuncTable.SignDataUpdate		= SignDataUpdate;
	cspFuncTable.SignDataFinal		= SignDataFinal;

	cspFuncTable.VerifyData			= VerifyData;
	cspFuncTable.VerifyDataInit		= VerifyDataInit;
	cspFuncTable.VerifyDataUpdate	= VerifyDataUpdate;
	cspFuncTable.VerifyDataFinal	= VerifyDataFinal;

#ifdef CDSA_1_0
	cspFuncTable.KeyExchGenParam	= KeyExchGenParam;
	cspFuncTable.KeyExchPhase1		= KeyExchPhase1;
	cspFuncTable.KeyExchPhase2		= KeyExchPhase2;
#endif

	cspFuncTable.GenerateAlgorithmParams = GenerateAlgorithmParams;
	cspFuncTable.DeriveKey			= DeriveKey;

	regInfo.Initialize			= Initialize;
	regInfo.Terminate			= Terminate;
	regInfo.EventNotify			= EventNotify;
	regInfo.ThreadSafe			= CSSM_FALSE; //CSSM_TRUE;
	regInfo.ServiceSummary		= CSSM_SERVICE_CSP;
	regInfo.NumberOfServiceTables = 1;
	regInfo.Services			= services;

	services[0].ServiceType = CSSM_SERVICE_CSP;
	services[0].CspFuncs = &cspFuncTable;

	if (CSSM_RegisterServices(&guid, &regInfo, &memFuncs, NULL) != CSSM_OK) {
		throw ObjInitException(CSSM_CSP_REGISTER_ERROR);
	}
}

CSP::~CSP() {
	CSSM_GUID	guid = IBMCYLINKCSP_GUID; // our GUID

	if (head != NULL)
		CloseAllSessions();

	if (CSSM_DeregisterServices (&guid) != CSSM_OK) {
		throw ObjInitException(CSSM_CSP_REGISTER_ERROR);
	}
}

Session* CSP::OpenSession(uint32 handle) {
	try {
		GetSession(handle);
		//if no exception was thrown then there already is 
		//a Session with this handle;
	} catch (InputException e) {
		if (e.errCode != CSSM_CSP_INVALID_CSP_HANDLE)
			throw e;

		Session *session = new Session(handle, &memFuncs);
		session->next = head;
		head = session;
		return(session);
	}

	throw InputException(CSSM_CSP_INVALID_CSP_HANDLE);
	return(NULL);
}

void CSP::CloseSession(uint32 handle) {
	Session	*session, *prev;
	for (session = head, prev = NULL; session!= NULL; prev = session, session = session->next) {
		if (session->cspHandle == handle) {
			if (session == head)
				head = session->next;
			else
				prev->next = session->next;

			delete session;
			return;
		}
	}

	//no session with that handle was found
	throw InputException(CSSM_CSP_INVALID_CSP_HANDLE);
}

void CSP::CloseAllSessions() {
	Session *session, *next;

	for (session = head; session != NULL; session = next) {
		next = session->next;
		delete session;
	}
	
	head = NULL;
}

Session* CSP::GetSession(uint32 handle) {
	for (Session *session = head; session != NULL; session = session->next) {
		if (session->cspHandle == handle)
			return(session);
	}

	throw InputException(CSSM_CSP_INVALID_CSP_HANDLE);
	return(NULL);
}

Context* CSP::GetContext(uint32 sessionHandle, uint32 contextHandle) {
	Session* session = GetSession(sessionHandle);
	return (session->GetContext(contextHandle));
}

uint8* CSP::malloc(CSSM_MODULE_HANDLE cspHandle, uint32 size) {
	if (size == 0)
		return(NULL);

	uint8* ptr = (uint8*)memFuncs.malloc_func(cspHandle, size);
	if (ptr == NULL)
		throw MemoryException(CSSM_MALLOC_FAILED);

	return(ptr);
}

uint8* CSP::calloc(CSSM_MODULE_HANDLE cspHandle, uint32 num, uint32 size) {
	uint8* ptr = (uint8*)memFuncs.calloc_func(cspHandle, num, size);
	if (ptr == NULL)
		throw MemoryException(CSSM_CALLOC_FAILED);

	return(ptr);
}

uint8* CSP::realloc(CSSM_MODULE_HANDLE cspHandle, uint8* memblock, uint32 size) {
	uint8* ptr = (uint8*)memFuncs.realloc_func(cspHandle, (void*)memblock, size);
	if (ptr == NULL)
		throw MemoryException(CSSM_REALLOC_FAILED);

	return(ptr);
}

void CSP::free(CSSM_MODULE_HANDLE cspHandle, uint8* memblock) {
	memFuncs.free_func(cspHandle, (uint8*)memblock);
	memblock = NULL;
}
