/* ***************************************************************** *
 * 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 "pkcsprivate.h"

//
// PKCSMSM Globally unique ID, defined in 'pkcsguid.h'
//

extern CSSM_GUID CssmGuid;
extern CSSM_SPI_MEMORY_FUNCS CssmMemFuncs;

MSMSESSION_PTR pMsmSessionList = NULL;
HANDLE IbmPkcsMsmMutex;




/*****************************************************************************
 * Function: NewMsmSession - Allocate a new MSMSESSION and tag it with 
 *               CssmModuleHandle
 *
 * Input:
 *  CssmModuleHandle  - Module handle 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  MSMSESSION_PTR    - Successful      
 *  NULL        - Failed
 *
 */

MSMSESSION_PTR CSSMAPI NewMsmSession(CSSM_MODULE_HANDLE CssmModuleHandle)
{
  MSMSESSION_PTR    pMsmSession;

#ifdef _DEBUG
  Message((LPCTSTR) "Enter NewMsmSession");
#endif

  pMsmSession = (MSMSESSION_PTR) calloc(1, sizeof(MSMSESSION));
  if (pMsmSession == NULL)
    SetErr(CSSM_CSP_MEMORY_ERROR);
  else
    pMsmSession->CssmModuleHandle = CssmModuleHandle;

#ifdef _DEBUG
  Message((LPCTSTR) "Exit NewMsmSession");
#endif
  
  return pMsmSession;
}



/*****************************************************************************
 * Function: DeleteMsmSession - Free the session pointed to by pMsmSession
 *
 * Input:
 *  pMsmSession   - Session to be freed 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  None
 *
 */

void CSSMAPI DeleteMsmSession(MSMSESSION_PTR pMsmSession)
{
  if (pMsmSession != NULL)
    free((void*) pMsmSession);
}



/*****************************************************************************
 * Function: InsertMsmSession - Insert pMsmSession into 'pMsmSessionList' list
 *
 * Input:
 *  pMsmSession   - Session to be inserted  
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI InsertMsmSession(MSMSESSION_PTR pMsmSession)
{

#ifdef _DEBUG
  Message((LPCTSTR) "Enter InsertMsmSession");
#endif

  if (cssm_LockMutex(IbmPkcsMsmMutex, CSSM_INFINITE_WAIT) != CSSM_MUTEX_LOCKED)
    return CSSM_FAIL;
  
  pMsmSession->pNext = pMsmSessionList;
  pMsmSessionList = pMsmSession;

#ifdef _DEBUG
  Message((LPCTSTR) "Exit InsertMsmSession");
#endif

  if (cssm_UnlockMutex(IbmPkcsMsmMutex) != CSSM_MUTEX_UNLOCKED)
    return CSSM_FAIL;
  else
    return CSSM_OK;
}


/*****************************************************************************
 * Function: RemoveMsmSession - Remove pMsmSession from 'pCmsContextList' list
 *
 * Input:
 *  pMsmSession   - Session to be removed 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI RemoveMsmSession(MSMSESSION_PTR pMsmSession)
{
  MSMSESSION_PTR  pPrev, pCurrent;

  if (cssm_LockMutex(IbmPkcsMsmMutex, CSSM_INFINITE_WAIT) != CSSM_MUTEX_LOCKED)
    return CSSM_FAIL;

  pPrev = NULL;
  pCurrent = pMsmSessionList;

  while (pCurrent != NULL) 
  {
    if (pCurrent == pMsmSession)
    {
      if (pPrev == NULL)
        pMsmSessionList = pCurrent->pNext;
      else
        pPrev->pNext = pCurrent->pNext;
      
      pMsmSession->pNext = NULL;
      break;
    }
    else
    {
      pPrev = pCurrent;
      pCurrent = pCurrent->pNext;
    }
  }

  if (cssm_UnlockMutex(IbmPkcsMsmMutex) != CSSM_MUTEX_UNLOCKED)
    return CSSM_FAIL;
  else
    return CSSM_OK;

}



/*****************************************************************************
 * Function: FindMsmSession - Find a MSM session given a CSSM Module Handle, 
 *                returning NULL if not found.
 *
 * Input:
 *  CssmModuleHandle    - Module handle 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  MSMSESSION_PTR    - Successful      
 *  NULL        - Failed
 *
 */

MSMSESSION_PTR CSSMAPI FindMsmSession(CSSM_MODULE_HANDLE CssmModuleHandle)
{
  MSMSESSION_PTR  pCurrent, pFound;

#ifdef _DEBUG
  Message((LPCTSTR) "Enter FindMsmSession");
#endif

  if (cssm_LockMutex(IbmPkcsMsmMutex, CSSM_INFINITE_WAIT) != CSSM_MUTEX_LOCKED)
    return NULL;
  
  pFound = NULL;
  pCurrent = pMsmSessionList;

  while (pCurrent != NULL) 
  {
    if (pCurrent->CssmModuleHandle == CssmModuleHandle)
    {
      pFound = pCurrent;
      break;
    }
    else
      pCurrent = pCurrent->pNext;
  }

#ifdef _DEBUG
  Message((LPCTSTR) "Exit FindMsmSession");
#endif

  if (cssm_UnlockMutex(IbmPkcsMsmMutex) != CSSM_MUTEX_UNLOCKED)
    return NULL;
  else
    return pFound;
}



/*****************************************************************************
 * Function: FindMsmSession2 - Find a MSM session given a PKCS11 session handle, 
 *                 returning NULL if not found.
 *
 * Input:
 *  PkcsSessionHandle - PKCS11 session handle 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  MSMSESSION_PTR    - Successful      
 *  NULL        - Failed
 *
 */

MSMSESSION_PTR CSSMAPI FindMsmSession2(CK_SESSION_HANDLE PkcsSessionHandle)
{
  MSMSESSION_PTR  pCurrent, pFound;

  if (cssm_LockMutex(IbmPkcsMsmMutex, CSSM_INFINITE_WAIT) != CSSM_MUTEX_LOCKED)
    return NULL;
  
  pFound = NULL;
  pCurrent = pMsmSessionList;

  while (pCurrent != NULL) 
  {
    if (pCurrent->PkcsSessionHandle == PkcsSessionHandle)
    {
      pFound = pCurrent;
      break;
    }
    else
      pCurrent = pCurrent->pNext;
  }

  if (cssm_UnlockMutex(IbmPkcsMsmMutex) != CSSM_MUTEX_UNLOCKED)
    return NULL;
  else
    return pFound;
}



/*****************************************************************************
 * Function: Message - Print a message, 
 *
 * Input:
 *  pMsg        - Message to be printed 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  None
 *
 */

void CSSMAPI Message(LPCTSTR pMsg)
{
  printf("PKCSMSM - %s\n", pMsg);
}



/*****************************************************************************
 * Function: SetErr - Map all PKCS error codes to CSSM_CSP_PRIVATE_ERROR range
 *            before setting the CSSM error field and returning CSSM_FAIL.
 *
 * Input:
 *  err         - Error code
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_FAIL     - Always
 *
 */

CSSM_RETURN CSSMAPI SetErr(uint32 err)
{
  if (err < CSSM_CSP_BASE_ERROR)
    err += CSSM_CSP_PRIVATE_ERROR;

  CSSM_SetError(&CssmGuid, err);
  return CSSM_FAIL;
}



/*****************************************************************************
 * Function: SetErrNull - Map all PKCS error codes to CSSM_CSP_PRIVATE_ERROR range
 *              before setting the CSSM error field and returning NULL
 *
 * Input:
 *  err         - Error code
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  NULL        - Always
 *
 */

void* CSSMAPI SetErrNull(uint32 err)
{
  if (err < CSSM_CSP_BASE_ERROR)
    err += CSSM_CSP_PRIVATE_ERROR;

  CSSM_SetError(&CssmGuid, err);
  return NULL;
}



/*****************************************************************************
 * Function: SetErrFalse - Map all PKCS error codes to CSSM_CSP_PRIVATE_ERROR range
 *                 before setting the CSSM error field and returning CSSM_FALSE
 * Input:
 *  err         - Error code
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_FALSE      - Always
 *
 */

CSSM_BOOL CSSMAPI SetErrFalse(uint32 err)
{
  if (err < CSSM_CSP_BASE_ERROR)
    err += CSSM_CSP_PRIVATE_ERROR;

  CSSM_SetError(&CssmGuid, err);
  return CSSM_FALSE;
}



/*****************************************************************************
 * Function: SetErrNullHandle - Map all PKCS error codes to CSSM_CSP_PRIVATE_ERROR range
 *                before setting the CSSM error field and returning a zero.
 * Input:
 *  err         - Error code
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  0         - Always
 *
 */

CSSM_HANDLE CSSMAPI SetErrNullHandle(uint32 err)
{
  if (err < CSSM_CSP_BASE_ERROR)
    err += CSSM_CSP_PRIVATE_ERROR;

  CSSM_SetError(&CssmGuid, err);
  return 0;
}



/*****************************************************************************
 * Function: ErrDestruct - Remove and delete MSM session before calling SetErr
 *
 * Input:
 *  pMsmSession     - Session to be destroyed
 *  err         - Error code
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_FAIL     - Always
 *
 */

CSSM_RETURN CSSMAPI ErrDestruct(MSMSESSION_PTR pMsmSession, uint32 err)
{
  if (pMsmSession != NULL)
  {
    RemoveMsmSession(pMsmSession);  // Ignore mutex error here if any to report real error
    DeleteMsmSession(pMsmSession);
  }

  return SetErr(err);
}


/*****************************************************************************
 * Function: Destruct - Remove and delete MSM session
 *
 * Input:
 *  pMsmSession     - Session to be destroyed
 *  err         - Error code
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - If successful
 *  CSSM_FAIL     - If failed
 *
 */

CSSM_RETURN CSSMAPI Destruct(MSMSESSION_PTR pMsmSession)
{
  if (pMsmSession != NULL)
  {
    if (RemoveMsmSession(pMsmSession) != CSSM_OK)
      return CSSM_FAIL;

    DeleteMsmSession(pMsmSession);
  }

  return CSSM_OK;
}


