/* SCCSID: fwk/cssm/contextbl.c, dss_cdsa_fwk, fwk_rel3, dss_980403 1.8 4/13/98 10:36:23 */
/* ***************************************************************** *
 * 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.                                                        *
 * ***************************************************************** */

/*
 * FILE: contextbl.c
 *
 * Contains KeyWorks F/W context hash table routines.
 *
 */
/*
 * (C) COPYRIGHT International Business Machines Corp. 1996, 1997
 * All Rights Reserved
 * Licensed Materials - Property of IBM
 *
 * Copyright (c) 1995, 1996, 1997 Intel Corporation. All rights reserved.
 *
 * US Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *
 */
/*
 * WARNING: EXPORT RESTRICTED.
 * This software listing contains cryptographic methods and technology.
 * It is export restricted by the Office of Defense Trade Controls, United
 * States Department of State and cannot be downloaded or otherwise
 * exported or re-exported (i) into (or to a national or resident of) Cuba,
 * Iraq, Libya, Yugoslavia, North Korea, Iran, Syria or any other country
 * to which the US has embargoed goods; or (ii) to anyone on the US
 * Treasury Department's list of Specially Designated Nationals or the US
 * Commerce Department's Table of Denial Orders. By downloading or using
 * this product, you are agreeing to the foregoing and you are representing
 * and warranting that you are not located in, under the control of, or a
 * national or resident of any such country or on any such list.
 */

#include "cssm.h"
#include "cssmport.h"
#include "internal.h"
#include "context.h"

/* function reference */
void CSSMAPI cssm_NotifyModule(CSSM_CSP_HANDLE cspHandle,CSSM_CC_HANDLE ccHandle,CSSM_EVENT_TYPE event);

/* index table */
static CtxHashTable	h_table[CTXTABLESZ];

 /*****************************************************************************
 * cssm_InitContextTable - initialize the hash table (all the locks)
 *	Should be called only once, from dllmain
 *
 * Input:
 *	none
 * Output:
 *	none
 * Return:
 *	CSSM_OK - success
 *  CSSM_FAIL - mutex failure
 */
CSSM_RETURN
cssm_InitContextTable(void)
{
	char	mutex_name[CMUTEXNAMESZ];
	int		i;

	memset(h_table, 0, sizeof(CtxHashTable)*CTXTABLESZ);
	memset (mutex_name, 0, CMUTEXNAMESZ);
	for (i=0; i < CTXTABLESZ; ++i)
	{
		// create mutex
		sprintf(mutex_name, "%s%d",CMUTEXNAME, i);
		h_table[i].lock = cssm_CreateMutex(mutex_name);
		if (h_table[i].lock == NULL)
		{
			CSSM_SetError(&cssm_GUID,CSSM_CANT_CREATE_MUTEX);
			return(CSSM_FAIL);
		}
	}
	return(CSSM_OK);
}

/*****************************************************************************
 * cssm_CleanContextTable - release locks
 * Input:
 *	none
 * Output:
 *	none
 * Return:
 *	CSSM_OK - success
 *  CSSM_FAIL - fail
 */
CSSM_RETURN
cssm_CleanContextTable(void)
{

	CtxHashEntryPtr	run, save;
	int	i;

	// free lists
	for (i=0; i < CTXTABLESZ; i++)
	{
		run = h_table[i].head;
		while (run)
		{
			save = run->next;
			// free context and hash entry
			cssm_RemoveCONTEXT(run->cssmCtxPtr->ContextHandle);
			run = save;
		}
	}

	// release mutex
	for (i=0; i < CTXTABLESZ; ++i)
	{
		if (cssm_CloseMutex(h_table[i].lock) != CSSM_OK)
			break;
	}

	// no global lock
	return(CSSM_OK);;
}

/*****************************************************************************
 * cssm_LookupCONTEXT - lookup a context handle. Called from a locked context.
 *
 * Input:
 *	ccHandle - context handle to look up
 * Output:
 *	none
 * Return:
 *	pContext - context ptr
 *	NULL - context not found
 */
cssm_INTERNALCONTEXT_PTR
cssm_LookupCONTEXT(CSSM_CC_HANDLE ccHandle)
{

	CtxHashEntryPtr           tablerun = NULL;
	cssm_INTERNALCONTEXT_PTR  pInternalCtx = NULL;
	CSSM_MUTEX                rcMutex = CSSM_MUTEX_ERROR;
	int                       i;

	i = HashContext(ccHandle);

	for (tablerun = h_table[i].head; tablerun; tablerun = tablerun->next) {
		if (tablerun->cssmCtxPtr->ContextHandle == ccHandle) {
#ifdef DEBUG
			printf("cssm_LookupCONTEXT Found CChandle: %i\n", ccHandle);
#endif
			pInternalCtx = tablerun->cssmCtxPtr;
			break;
		}
	}

	return(pInternalCtx);
}

/*****************************************************************************
 * cssm_InstallCONTEXT - install entry in the hash table
 *
 * Input:
 *	pContext - internal cssm context to insert
 * Output:
 *	none
 * Return:
 *	CSSM_OK - success
 *	CSSM_FAIL - operation failed
 */
CSSM_RETURN
cssm_InstallCONTEXT(cssm_INTERNALCONTEXT_PTR pIContext)
{

	CtxHashEntryPtr inew = NULL;
	CtxHashEntryPtr tablerun = NULL;
	CSSM_MUTEX	    rcMutex = CSSM_MUTEX_ERROR;
	CSSM_CC_HANDLE  newHandle = 0;
	CSSM_BOOL       duplicate = CSSM_FALSE;
	int i;

	inew = (CtxHashEntryPtr) cssm_calloc(sizeof(CtxHashEntry),1, NULL);
	if (!inew) {
		CSSM_SetError(&cssm_GUID, CSSM_CALLOC_FAILED);
		return(CSSM_FAIL);
	}

	inew->cssmCtxPtr = pIContext;

	do {
		// generate contex handle
		newHandle = (CSSM_HANDLE)cssm_Rand(CSSM_CCHANDLE);
		i = HashContext(newHandle);

	#ifdef DEBUG
		printf("cssm_IstallCONTEXT: insert in slot: %d\n",i);
				printf("cssm_IstallCONTEXT %i ", pIContext->ContextHandle);
	#endif
		rcMutex = cssm_LockMutex (h_table[i].lock, CSSM_INFINITE_WAIT);
		if(rcMutex != CSSM_MUTEX_LOCKED) {
			CSSM_SetError(&cssm_GUID, CSSM_LOCK_MUTEX_FAILED);
			cssm_free(inew, NULL);
			return(CSSM_FAIL);;
		}

		// check for dupliactes
		duplicate = CSSM_FALSE;
		for (tablerun = h_table[i].head; tablerun; tablerun = tablerun->next) {
			if (tablerun->cssmCtxPtr->ContextHandle == newHandle) {
				if (cssm_UnlockMutex(h_table[i].lock) == CSSM_MUTEX_ERROR) {
					CSSM_SetError(&cssm_GUID, CSSM_UNLOCK_MUTEX_FAILED);
					cssm_free (inew, 0);
					return(CSSM_FAIL);
				}
				else {
					duplicate = CSSM_TRUE;;
				}
			}
		}
		if (duplicate == CSSM_TRUE)
			continue;

		// add new entry
		pIContext->ContextHandle = newHandle;
		inew->next = h_table[i].head;
		h_table[i].head = inew;

		rcMutex = cssm_UnlockMutex(h_table[i].lock);
		if (rcMutex == CSSM_MUTEX_ERROR) {
			CSSM_SetError(&cssm_GUID, CSSM_UNLOCK_MUTEX_FAILED);
			// we clean up on detach
			return(CSSM_FAIL);
		}
		else
			return(CSSM_OK);
	} while(1);
}

/*****************************************************************************
 * cssm_RemoveCONTEXT - remove this context from the appropriate hash
 * list
 *
 * Input:
 *	ccHandle - context handle to look up
 * Output:
 *	none
 * Return:
 *	CSSM_OK - success
 *  CSSM_FAIL - mutex lock error
 */
CSSM_RETURN
cssm_RemoveCONTEXT(CSSM_CC_HANDLE ccHandle)
{
	CtxHashEntryPtr run = NULL;
	CtxHashEntryPtr last = NULL;
	CSSM_MUTEX	    rcMutex = CSSM_MUTEX_ERROR;
	CSSM_CSP_HANDLE cspHandle = 0;
	CSSM_RETURN     rc = CSSM_FAIL;
	CSSM_BOOL		found = CSSM_FALSE;
	int i;

	i = HashContext(ccHandle);
	rcMutex = cssm_LockMutex (h_table[i].lock, CSSM_INFINITE_WAIT);
	if(rcMutex != CSSM_MUTEX_LOCKED) {
		CSSM_SetError(&cssm_GUID, CSSM_LOCK_MUTEX_FAILED);
		return(CSSM_FAIL);
	}

	last = run = h_table[i].head;
	while (run) {
		/* check context handle */
		if (run->cssmCtxPtr->ContextHandle == ccHandle) {
			if (last == run) 	/* at head */
				h_table[i].head = h_table[i].head->next;
			else
				last->next = run->next;
 
			cssm_FreeIntContext (run->cssmCtxPtr, CSSM_EVENT_DELETE_CONTEXT, CSSM_TRUE);
			cspHandle = run->cssmCtxPtr->CSPHandle;
			cssm_free(run, NULL);
			run = NULL;
			found = CSSM_TRUE;
			break;
		} else {
			last = run;
			run = run->next;
		}
	}

	rcMutex = cssm_UnlockMutex(h_table[i].lock);
	if (rcMutex == CSSM_MUTEX_ERROR) {
		CSSM_SetError(&cssm_GUID, CSSM_UNLOCK_MUTEX_FAILED);
		rc = CSSM_FAIL;
	} else {
		if (!found) {
#ifdef _DEBUG
			printf("cssm_RemoveCONTEXT context: %d NOT FOUND\n", ccHandle);
#endif
			CSSM_SetError(&cssm_GUID, CSSM_INVALID_CONTEXT_HANDLE);
			rc = CSSM_FAIL;
		} else {
			/* no need to check for NotifyModule errors */
			cssm_NotifyModule(cspHandle, ccHandle, CSSM_EVENT_DELETE_CONTEXT);
			rc = CSSM_OK;
		}
	}
	return(rc);
}

/*****************************************************************************
 * cssm_LookupAndLockBucket - Lookup an internal context and lock the bucket
 *                            if found. We do so to preserve the routines for
 *                            duplication and update of context and attributes.
 *
 * Input:
 *	ccHandle - context handle to look up
 *  index    - integer pointer to hold the hash index
 * Output:
 *	none
 * Return:
 *	cssmCtxPtr - if the context was found and bucket was locked
 *	NULL - context not found or lock error
 */
cssm_INTERNALCONTEXT_PTR
cssm_LookupAndLockBucket(CSSM_CC_HANDLE ccHandle, int *index)
{
	CtxHashEntryPtr tablerun = NULL;
	CSSM_MUTEX	    rcMutex = CSSM_MUTEX_ERROR;
	int i;

	i = HashContext(ccHandle);
	rcMutex = cssm_LockMutex (h_table[i].lock, CSSM_INFINITE_WAIT);
	if(rcMutex != CSSM_MUTEX_LOCKED) {
		CSSM_SetError(&cssm_GUID, CSSM_LOCK_MUTEX_FAILED);
		*index = -1;
		return(NULL);;
	}

	// lookup context
	for (tablerun = h_table[i].head; tablerun;
				     tablerun = tablerun->next) {
		if (tablerun->cssmCtxPtr->ContextHandle == ccHandle) {
#ifdef DEBUG
			printf("cssm_LookupAndLockBucket: Found %d\n", ccHandle);
			//PrintContext - to check distribution
#endif
			// keep the bucket locked
			*index = i;
			return(tablerun->cssmCtxPtr);
		}
	}

	// context not found
	rcMutex = cssm_UnlockMutex(h_table[i].lock);
	if (rcMutex == CSSM_MUTEX_ERROR) {
		// this should not happen)
		CSSM_SetError(&cssm_GUID, CSSM_UNLOCK_MUTEX_FAILED);
		*index = -1;
		return(NULL);;
	}

	// set the error
	CSSM_SetError(&cssm_GUID, CSSM_INVALID_CONTEXT_HANDLE);
#ifdef _DEBUG
	printf("cssm_LookupAndLockBucket: %d NOT Found\n", ccHandle);
#endif
	return(NULL);
}

/*****************************************************************************
 * cssm_UnlockBucket - Unlock a bucket locked in a lookup and lock request
 *
 * Input:
 *	ccHandle - context handle to look up
 * Output:
 *	none
 * Return:
 *	CSSM_OK - success
 *	CSSM_FAIL - failure
 */
CSSM_RETURN
cssm_UnlockBucket(int index)
{
	uint32 rc;

	if (index < 0 || index > CTXTABLESZ) {
		CSSM_SetError(&cssm_GUID, CSSM_BAD_HASH_CONTEXT_INDEX);
		return(CSSM_FAIL);
	}

	rc = cssm_UnlockMutex(h_table[index].lock);
	if (rc == CSSM_MUTEX_ERROR) {
		CSSM_SetError(&cssm_GUID, CSSM_UNLOCK_MUTEX_FAILED);
		return(CSSM_FAIL);
	}
	else
		return(CSSM_OK);
}

/*****************************************************************************
 * cssm_UpdateContextPtr - Lock the given bucket and update a context with the
 *							supplied context
 *
 * Input:
 *	ccHandle - context handle to look up
 *  newContext - context to update with
 * Output:
 *	none
 * Return:
 *	CSSM_OK - success
 *	CSSM_FAIL - failure
 */
CSSM_RETURN
cssm_UpdateContextPtr(CSSM_CC_HANDLE	ccHandle, CSSM_CONTEXT_PTR newContext)
{
	CSSM_MUTEX	rcMutex;
	uint32		i;
	CtxHashEntryPtr tablerun = NULL, parent=NULL;
	CSSM_BOOL	found= CSSM_FALSE;
	cssm_INTERNALCONTEXT	oldContext = {0,0,0};
	CSSM_RETURN	rc= CSSM_OK;
	CSSM_CONTEXT_ATTRIBUTE_PTR pAtt;

	/* we only allow updates for the same CSP id */
	pAtt = CSSM_GetContextAttribute(newContext, CSSM_ATTRIBUTE_CSP_HANDLE);
	if (pAtt==NULL) {
		/* error code already set */
		return(CSSM_FAIL);
	}


	i = HashContext(ccHandle);

	rcMutex = cssm_LockMutex (h_table[i].lock, CSSM_INFINITE_WAIT);
	if(rcMutex != CSSM_MUTEX_LOCKED) {
		CSSM_SetError(&cssm_GUID, CSSM_LOCK_MUTEX_FAILED);
		return(CSSM_FAIL);;
	}

	for (tablerun = h_table[i].head; tablerun; tablerun = tablerun->next) {
		if (tablerun->cssmCtxPtr->ContextHandle == ccHandle) {
			found = CSSM_TRUE;
			break;
		}
	}

	if (!found) {
		CSSM_SetError(&cssm_GUID, CSSM_INVALID_CONTEXT_HANDLE);
		rc = CSSM_FAIL;
	} else {
		/* make sure CSP handles match */
		if (pAtt->Attribute.Uint32 == tablerun->cssmCtxPtr->CSPHandle) {
			oldContext = *(tablerun->cssmCtxPtr);
			tablerun->cssmCtxPtr->Context = newContext;
		} else {
			CSSM_SetError(&cssm_GUID, CSSM_INVALID_CSP_HANDLE);
			rc = CSSM_FAIL;
		}
	}

	rcMutex = cssm_UnlockMutex(h_table[i].lock);
	if (rcMutex == CSSM_MUTEX_ERROR) {
		CSSM_SetError(&cssm_GUID, CSSM_UNLOCK_MUTEX_FAILED);
		rc= CSSM_FAIL;
	}

	/* delete the old context and send an update signal to the
	 * CSP that uses the old context
	 */
	if (oldContext.Context) {
		cssm_FreeIntContext (&oldContext, CSSM_EVENT_UPDATE_CONTEXT, CSSM_FALSE);
	}

	return(rc);

}


#ifdef _DEBUG
/*****************************************************************************
 * cssm_PrintContextTable - Hash table print utility.
 *
 * Input:
 *	none
 * Output:
 *	none
 * Return:
 *	none
 */
void
cssm_PrintContextTable(void)
{
	CtxHashEntryPtr run;
	int i;

	for (i=0; i < CTXTABLESZ; i++)
	{
		if ((run = h_table[i].head) == 0)
			continue;
		printf("bucket: %d\n",i);
		while (run)
		{
			printf("\t\tid=%d\n ",run->cssmCtxPtr->ContextHandle);
			run = run->next;
		}
	}
	printf("\nEnd Context_table\n");
}
#endif // _DEBUG

