/* SCCSID: fwk/cssm/addutil.c, dss_cdsa_fwk, fwk_rel1, rel1_level1 1.8 8/10/97 10:42:33 */

/* ***************************************************************** *
 * 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:   ADDUTIL.C
 *
 * This file contains the functions that are contained in the add-in util
 * of the CSSM 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 "context.h"
#include <time.h>

/*----------------------------------------------------------
 *Name: cssm_CheckInit
 *
 *Description:
 * Make sure that client has initialize the CSSM.
 *
 *Parameters:
 * None
 *
 *Returns:
 * CSSM_FAIL - Client has not initialize the CSSM
 * CSSM_OK - Client has initialize the CSSM
 *
 *--------------------------------------------------------*/
CSSM_RETURN CSSMAPI cssm_CheckInit (void)
{

    if (app_malloc == NULL) {
        CSSM_SetError (&cssm_GUID, CSSM_NOT_INITIALIZE);
        return(CSSM_FAIL);
    } else
        return(CSSM_OK);
}

/*----------------------------------------------------------
 *Name: cssm_ModuleUninstall
 *
 *Description:
 * Remove an add-in from visibilty by the CSSM.
 *
 *Parameters:
 * GUID (input) - GUID that describes the add-in
 *
 *Returns:
 * CSSM_OK - call is successful
 * CSSM_INVALID_POINTER - invalid pointer
 *--------------------------------------------------------*/
CSSM_RETURN CSSMAPI cssm_ModuleUninstall (const CSSM_GUID_PTR GUID)
{
	CSSM_RETURN	rc;

    /* Check validity of pointers */

    if (GUID == 0 || cssm_IsBadReadPtr(GUID, sizeof (CSSM_GUID))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    /* Clean up internal structures */
    rc = cssm_RegRemoveModule (GUID);
	return(rc);
}

/*----------------------------------------------------------
 *Name: cssm_Rand
 *
 *Description:
 * Generate a 32 bit random number and make sure that there
 * is no collision in its usage space.
 *
 *Parameters:
 * None
 *
 *Returns:
 * 32 bit random number
 *
 *--------------------------------------------------------*/
uint32 cssm_Rand (cssm_RAND_TYPE type)
{
	static uint32 value;
    int Done = 0;

    while (Done == 0 ) {
        /* use C runtime functions */
        srand ((uint32)time (NULL));
        value ^= rand();
        value <<= 16;
        srand (value);
        value ^= rand();

		if (value == 0)
			continue;

        /* check for collision */
        if (type == CSSM_CCHANDLE) {
			/* cssm_InstallContext does the ckeck */
            Done = 1;
        } else {
            /* test for collision in add-in lists */
            if (cssm_GetModuleByHandle (value, NULL, NULL) != CSSM_OK)
                Done = 1;
        }
    }

    return(value);
}
/*----------------------------------------------------------
 *Name: cssm_CheckAPIMemFuncs
 *
 *Description:
 * Check to make sure that memory functions are initialize
 *
 *Parameters:
 * MemoryFunctions (input) - pointer to memory function structure
 *
 *Returns:
 * CSSM_FAIL - bad pointer somewhere
 * CSSM_OK - all pointers OK
 *
 *--------------------------------------------------------*/
CSSM_RETURN cssm_CheckAPIMemFuncs (
                           const CSSM_API_MEMORY_FUNCS_PTR MemoryFunctions)
{
    /* Check validity of pointers passed in */

    if (cssm_IsBadReadPtr (MemoryFunctions, sizeof (CSSM_API_MEMORY_FUNCS))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    /* Check validity of callbacks */
    if (cssm_IsBadCodePtr((CSSM_CALLBACK)MemoryFunctions->malloc_func)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadCodePtr((CSSM_CALLBACK)MemoryFunctions->realloc_func)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadCodePtr((CSSM_CALLBACK)MemoryFunctions->free_func)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadCodePtr((CSSM_CALLBACK)MemoryFunctions->calloc_func)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    return(CSSM_OK);
}

/*----------------------------------------------------------
 *Name: cssm_CheckCopy
 *
 *Description:
 * Check to make sure that memory buffers are valid before
 * performing the copy operation
 *
 *Parameters:
 * Dest (input) - pointer to destination memory buffer
 * Src (input) - pointer to source memory buffer
 * size (input) - size of data to copy
 *
 *Returns:
 * CSSM_FAIL - bad pointer somewhere
 * CSSM_OK - memory is copied
 *
 *--------------------------------------------------------*/
CSSM_RETURN cssm_CheckCopy (void *Dest, void *Src, uint32 size)
{
    /* Check validity of pointers passed in */

    if (cssm_IsBadReadPtr (Src, size)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadWritePtr (Dest, size)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_memcpy (Dest, Src, size) == NULL) {
        CSSM_SetError (&cssm_GUID, CSSM_MEMORY_ERROR);
        return(CSSM_FAIL);
    }

    return(CSSM_OK);
}

/*---------------------------------------------------------------
 *
 *Name: cssm_ModuleInstall
 *
 *Description:
 *   Internal function that installs the addin information into
 *   the registry.
 *
 *Parameters:
 *   ModuleName (input) - name of addin module
 *   ModuleFileName (input) - name of file that implements addin module
 *   ModulePathName (input) -  path to file of addin module
 *   GUID (input) -  GUID of addin module
 *   ModuleDescription (input) -  Description of addin module
 *   Reserved1 (input) -  Reserved data
 *   Reserved2 (input) -  Reserved data
 *
 *Returns:
 *   CSSM_FAIL - unable to complete update to registry
 *   CSSM_OK - registry has updated information
 *
 *-------------------------------------------------------------*/
CSSM_RETURN CSSMAPI cssm_ModuleInstall (
                                 const char *ModuleName,
                                 const char *ModuleFileName,
                                 const char *ModulePathName,
                                 const CSSM_GUID_PTR GUID,
                                 const CSSM_MODULE_INFO_PTR ModuleDescription,
                                 const void * Reserved1,
                                 const CSSM_DATA_PTR Reserved2)
{
	CSSM_RETURN	rc;

    /* Make sure all pointer are valid */

    if (cssm_IsBadReadPtr(ModuleName, 1)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadStrPtr(ModuleName,strlen(ModuleName))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadReadPtr(ModuleFileName, 1)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }
    if (cssm_IsBadStrPtr(ModuleFileName,strlen(ModuleFileName))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadReadPtr(ModulePathName, 1)) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }
    if (cssm_IsBadStrPtr(ModulePathName,strlen(ModulePathName))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadReadPtr(GUID, sizeof(CSSM_GUID_PTR))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    if (cssm_IsBadReadPtr(ModuleDescription, sizeof(CSSM_MODULE_INFO_PTR))) {
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

    /* update registry with the add in information */
    rc = cssm_RegWriteModule (ModuleName, ModuleFileName, ModulePathName,
                               GUID, ModuleDescription, Reserved1, Reserved2);
	return(rc);
}

/*---------------------------------------------------------------
 *
 *Name: cssm_FreeModule
 *
 *Description:
 *   Internal function that frees module description structure.
 *
 *Parameters:
 *   ModuleDescription (input) -  Description of addin module
 *
 *Returns:
 *   CSSM_FAIL - unable to free structure
 *   CSSM_OK - structure is freed
 *
 *-------------------------------------------------------------*/
CSSM_RETURN cssm_FreeModule (const CSSM_MODULE_INFO_PTR ModuleDescription)
{
    uint32 i, Result = CSSM_OK;	


    if (cssm_IsBadReadPtr(ModuleDescription, sizeof(CSSM_MODULE_INFO))) {  
        CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
        return(CSSM_FAIL);
    }

	if (ModuleDescription->ServiceList == NULL)
	{
		CSSM_SetError (&cssm_GUID, CSSM_INVALID_POINTER);
		return(CSSM_FAIL);
	}

    if (ModuleDescription->ServiceMask != CSSM_SERVICE_CSSM) {
        CSSM_SERVICE_INFO_PTR Service;

        Service = ModuleDescription->ServiceList;
        for (i=0; i<ModuleDescription->NumberOfServices; i++) {
            switch (Service[i].Type) {
                uint32 j;

                case CSSM_SERVICE_TP:
                    for (j=0; j<Service[i].NumberOfSubServices; j++)
                        Result |= cssm_FreeTPSubService (&Service[i].TpSubServiceList[j]);

                    app_free (Service[i].TpSubServiceList, memRef);
                break;

                case CSSM_SERVICE_CSP:
                    for (j=0; j<Service[i].NumberOfSubServices; j++)
                        Result |= cssm_FreeCSPSubService (&Service[i].CspSubServiceList[j]);

                    app_free (Service[i].CspSubServiceList, memRef);	
                break;

                case CSSM_SERVICE_CL:
                    for (j=0; j<Service[i].NumberOfSubServices; j++)
                        Result |= cssm_FreeCLSubService (&Service[i].ClSubServiceList[j]);

                    app_free (Service[i].ClSubServiceList, memRef);	
				break;
				
                case CSSM_SERVICE_DL:
                    for (j=0; j<Service[i].NumberOfSubServices; j++)
                        Result |= cssm_FreeDLSubService (&Service[i].DlSubServiceList[j]);

                    app_free (Service[i].DlSubServiceList, memRef);		
                break;
            }

            if (Result != CSSM_OK)
                return(Result);
		}
    }

	app_free (ModuleDescription->ServiceList, memRef);	
    app_free (ModuleDescription, memRef);

    return(Result);
}
