/* SCCSID: fwk/cssm/spi.c, dss_cdsa_fwk, fwk_rel3, dss_980403 1.14 4/13/98 10:37:39 */
/* ***************************************************************** *
 * 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:   SPI.C
 *
 * This file contains the functions that are contained in the SPI portion
 * of the CSSM exported functions.
 */
/*
 * (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 "cssmcspi.h"
#include "addin.h"

extern HANDLE hCssmAddinMutex;
/*---------------------------------------------------------------
 *
 *Name: cssm_RegisterService
 *
 *Description:
 *   Generic function for all add-in registration
 *
 *Parameters:
 *  GUID - guid of add-in
 *  JumpTable - functions provided by the add-in
 *  UpcallTable - table for return the memory functions
 *  AddInType- the type of add-in
 *
 *Returns:
 *   CSSM_FAIL - unable to complete registration
 *   CSSM_OK - registration completed
 *
 *-------------------------------------------------------------*/
CSSM_RETURN CSSMAPI CSSM_RegisterServices(
	const CSSM_GUID_PTR GUID,
    const CSSM_REGISTRATION_INFO_PTR FunctionTable,
    CSSM_SPI_MEMORY_FUNCS_PTR UpcallTable,
    void *Reserved)
{
	CSSM_RETURN	rc;

    /* clear the error */

    CSSM_ClearError ();

    /* Check validity of pointers passed in */
    if (cssm_IsBadReadPtr (UpcallTable, sizeof (CSSM_SPI_MEMORY_FUNCS))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    /* Initialize the upcall memory table */
    UpcallTable->malloc_func = InternalMemoryFuncs.malloc_func;
    UpcallTable->free_func = InternalMemoryFuncs.free_func;
    UpcallTable->realloc_func = InternalMemoryFuncs.realloc_func;
    UpcallTable->calloc_func = InternalMemoryFuncs.calloc_func;

    /* Load the library and initialize */
    rc = cssm_NewModuleRecord (GUID, FunctionTable);
	return(rc);
}

/*---------------------------------------------------------------
 *
 *Name: CSSM_DeregisterServices
 *
 *Description:
 *   Generic function for deregistering of add-in with CSSM
 *
 *Parameters:
 *  GUID - guid of add-in
 *  AddInType- the type of add-in
 *
 *Returns:
 *   CSSM_FAIL - unable to complete deregistration
 *   CSSM_OK - deregistration completed
 *
 *-------------------------------------------------------------*/
CSSM_RETURN CSSMAPI CSSM_DeregisterServices (const CSSM_GUID_PTR GUID)
{
	CSSM_RETURN	rc;

    /* clear the error */

    CSSM_ClearError ();

    /* Check validity of incoming pointers */
    if (cssm_IsBadReadPtr(GUID, sizeof (CSSM_GUID))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    /* Fetch the library handle by the name passed in. If the handle doen't
     * exist, exit with on OK code since it doesn't matter.
     */
    rc = cssm_RemoveAddInRecord (GUID);
	return(rc);
}


/*---------------------------------------------------------------
 *
 *Name: cssm_dynamic_getinfo
 *
 *Description:
 *   Using the callback from the addin to get module information
 *   from it.
 *
 *Parameters:
 *  GUID - guid of add-in
 *  UsageMask - which addin type to get info on
 *  SubserviceID - internal ID for the subservice
 *  InfoLevel - the type of info to return in module info
 *
 *Returns:
 *   not NULL - pointer to the module info structure
 *   NULL - error
 *
 *-------------------------------------------------------------*/
CSSM_MODULE_INFO_PTR cssm_dynamic_getinfo(
	const CSSM_GUID_PTR GUID,
    CSSM_SERVICE_MASK UsageMask,
    uint32 SubserviceID,
    CSSM_INFO_LEVEL InfoLevel)
{
    CSSM_HANDLE handle;
    CSSM_REGISTRATION_INFO_PTR CallBack;
    CSSM_MODULE_INFO_PTR info = NULL;
    CSSM_VERSION Version;
    CSSM_API_MEMORY_FUNCS MemoryFuncs;

	MemoryFuncs.malloc_func		= app_malloc;
	MemoryFuncs.free_func		= app_free;
	MemoryFuncs.realloc_func	= app_realloc;
	MemoryFuncs.calloc_func		= app_calloc;
	MemoryFuncs.AllocRef		= memRef;

    /* Attach to the CSP; use the INFOATTACH event type
     * to do a "light" attach
	 */

	// it would be nice to lock
    if(cssm_LockMutex (hCssmAddinMutex, CSSM_INFINITE_WAIT) != CSSM_MUTEX_LOCKED) {
        return(NULL);
    }

	// expects caller to lock
    handle = cssm_ModuleAttach (GUID, &Version, &MemoryFuncs,
                                0, 0, 0, NULL,
                                CSSM_EVENT_INFOATTACH, CSSM_EVENT_INFODETACH);

    if (handle == 0) {
		if (cssm_UnlockMutex (hCssmAddinMutex) != CSSM_MUTEX_UNLOCKED) {
			return(NULL);
		}
    }

	// notify addin
    CallBack  = cssm_GetModuleCallBackByHandle (handle);

    if (CallBack) {

        if (CallBack->GetModuleInfo) {

			/* notice that the second parameter - addin type - is 0; for as it*/
			/* turns out neither cssm_GetMultitaskMutexHandle() nor */
			/* cssm_CheckThreadSafe() need sit - they just look at the handle */
			if( cssm_CheckThreadSafe(handle, 0) == CSSM_FALSE) {
				if (cssm_LockMutex(cssm_GetMultitaskMutexHandle (handle, 0),CSSM_INFINITE_WAIT) != CSSM_MUTEX_LOCKED) {
					// cssm error is set
					return(NULL);
				}
			}

            info = CallBack->GetModuleInfo(handle, UsageMask, SubserviceID, InfoLevel);

			/* notice that the second parameter - addin type - is 0; for as it*/
			/* turns out neither cssm_GetMultitaskMutexHandle() nor */
			/* cssm_CheckThreadSafe() need sit - they just look at the handle */
			if(cssm_CheckThreadSafe (handle, 0) == CSSM_FALSE) {
				if (cssm_UnlockMutex(cssm_GetMultitaskMutexHandle (handle,0)) != CSSM_MUTEX_UNLOCKED) {
					// cssm error is set
					return(NULL);
				}
			}

        } else {
            CSSM_SetError (&cssm_GUID, CSSM_FUNCTION_NOT_IMPLEMENTED);
		}
    }

    cssm_AddInDetach(handle, CSSM_EVENT_INFODETACH);

	// clean the stage
	if (cssm_UnlockMutex (hCssmAddinMutex) != CSSM_MUTEX_UNLOCKED) {
		return(NULL);
	}

    return(info);
}
