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

// This module is completely platform-specific.

#if OS == WIN32

#include <windows.h>
#include <process.h>

static HANDLE global_lock = 0;


static void acquire_global_lock(void) {
	HANDLE temp_handle;

	if (global_lock == 0) {
// We're probably the first thread to try to acquire this lock
// Do things carefully, though, just in case another thread is also trying...

		temp_handle = CreateMutex(NULL,
															false,
														  "PKI_MUTEX_LOCK"); 
// Now we have a handle to the mutex.  Lock it...		
		if (WaitForSingleObject(temp_handle, INFINITE) == WAIT_FAILED) {
			CloseHandle(temp_handle);
			abort();
		};
// Now we hold the mutex.  If we were first, we created the mutex; if not,
// we just created a new handle to it.  As we hold the mutex, we can now
// reliably check the global_lock variable to see whether anyone else has 
// already set it.

		if (global_lock == 0) {
// We created the mutex.  Publish the handle...
			global_lock = temp_handle;
			ReleaseMutex(temp_handle);
		} else {
// Someone else already created this mutex, and we just got another handle to it.
			ReleaseMutex(temp_handle);
			CloseHandle(temp_handle);
		};
	};
// Now we're sure that the mutex exists, and that global_lock contains the handle 
// for it, but we don't hold it.  Wait on it.
	if (WaitForSingleObject(global_lock, INFINITE) == WAIT_FAILED) abort();
}

static void release_global_lock(void) {
  ReleaseMutex(global_lock);
} 
 



pki_thread_handle_t pkiStartTask(void (APILINKAGE *function)(void *),
                                 void * params) {
	pki_thread_handle_t thread_handle;
	
	thread_handle = _beginthread(function, 0, params);
	
	if (thread_handle == (unsigned long)(-1)) return 0;

	return thread_handle;
}


void pkiTerminateTask(void) {
	_endthread();
}


int pkiCreateMutex(pki_mutex_t * mutex, int locked) {
	int result = 0;

	acquire_global_lock();
	__try {
		if (*mutex != PKI_MUTEX_INIT) {
			result = PKI_MUTEX_EXISTS;
		} else {
		  *mutex = CreateMutex(NULL, locked, NULL);
		};
	} 
	__finally {
		release_global_lock();
	};
	if ((result == PKI_MUTEX_EXISTS) && locked) {
		if ((result = pkiLockMutex(mutex)) == 0) return 0;
		return result;
	};
	
	return result;
}

int pkiLockMutex(pki_mutex_t * mutex) {
	int result;
	if ((result = WaitForSingleObject(*mutex, INFINITE)) == WAIT_OBJECT_0) return 0;
	return PKI_MUTEX_ERROR;
}

int pkiUnlockMutex(pki_mutex_t * mutex) {
  if (ReleaseMutex(*mutex)) return 0;
  return PKI_MUTEX_ERROR;
}

int pkiDestroyMutex(pki_mutex_t * mutex) {
	HANDLE handle;
	acquire_global_lock();
	__try {
    handle = *mutex;
    *mutex = PKI_MUTEX_INIT;
	} __finally {
    release_global_lock();
	};
	if (handle == PKI_MUTEX_INIT) return 0;
	if (CloseHandle(handle))  return 0;
	return PKI_MUTEX_ERROR;
}


int pkiSleep(unsigned long duration) {
  DWORD delta;
  delta = duration * 1000;
  Sleep(delta);
  return 0;
}


#else
#error Operating system not supported
#endif
