/*
             Common Public License Version 0.5

             THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF
             THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE,
             REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
             RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

             1. DEFINITIONS

             "Contribution" means: 
                   a) in the case of the initial Contributor, the
                   initial code and documentation distributed under
                   this Agreement, and 

                   b) in the case of each subsequent Contributor:
                   i) changes to the Program, and
                   ii) additions to the Program;

                   where such changes and/or additions to the Program
                   originate from and are distributed by that
                   particular Contributor. A Contribution 'originates'
                   from a Contributor if it was added to the Program
                   by such Contributor itself or anyone acting on such
                   Contributor's behalf. Contributions do not include
                   additions to the Program which: (i) are separate
                   modules of software distributed in conjunction with
                   the Program under their own license agreement, and
                   (ii) are not derivative works of the Program.

             "Contributor" means any person or entity that distributes
             the Program.

             "Licensed Patents " mean patent claims licensable by a
             Contributor which are necessarily infringed by the use or
             sale of its Contribution alone or when combined with the
             Program. 

             "Program" means the Contributions distributed in
             accordance with this Agreement.

             "Recipient" means anyone who receives the Program under
             this Agreement, including all Contributors.

             2. GRANT OF RIGHTS

                   a) Subject to the terms of this Agreement, each
                   Contributor hereby grants Recipient a
                   non-exclusive, worldwide, royalty-free copyright
                   license to reproduce, prepare derivative works of,
                   publicly display, publicly perform, distribute and
                   sublicense the Contribution of such Contributor, if
                   any, and such derivative works, in source code and
                   object code form.

                   b) Subject to the terms of this Agreement, each
                   Contributor hereby grants Recipient a
                   non-exclusive, worldwide, royalty-free patent
                   license under Licensed Patents to make, use, sell,
                   offer to sell, import and otherwise transfer the
                   Contribution of such Contributor, if any, in source
                   code and object code form. This patent license
                   shall apply to the combination of the Contribution
                   and the Program if, at the time the Contribution is
                   added by the Contributor, such addition of the
                   Contribution causes such combination to be covered
                   by the Licensed Patents. The patent license shall
                   not apply to any other combinations which include
                   the Contribution. No hardware per se is licensed
                   hereunder.

                   c) Recipient understands that although each
                   Contributor grants the licenses to its
                   Contributions set forth herein, no assurances are
                   provided by any Contributor that the Program does
                   not infringe the patent or other intellectual
                   property rights of any other entity. Each
                   Contributor disclaims any liability to Recipient
                   for claims brought by any other entity based on
                   infringement of intellectual property rights or
                   otherwise. As a condition to exercising the rights
                   and licenses granted hereunder, each Recipient
                   hereby assumes sole responsibility to secure any
                   other intellectual property rights needed, if any.

                   For example, if a third party patent license is
                   required to allow Recipient to distribute the
                   Program, it is Recipient's responsibility to
                   acquire that license before distributing the
                   Program.

                   d) Each Contributor represents that to its
                   knowledge it has sufficient copyright rights in its
                   Contribution, if any, to grant the copyright
                   license set forth in this Agreement.

             3. REQUIREMENTS

             A Contributor may choose to distribute the Program in
             object code form under its own license agreement, provided
             that:
                   a) it complies with the terms and conditions of
                   this Agreement; and

                   b) its license agreement:
                   i) effectively disclaims on behalf of all
                   Contributors all warranties and conditions, express
                   and implied, including warranties or conditions of
                   title and non-infringement, and implied warranties
                   or conditions of merchantability and fitness for a
                   particular purpose;

                   ii) effectively excludes on behalf of all
                   Contributors all liability for damages, including
                   direct, indirect, special, incidental and
                   consequential damages, such as lost profits;

                   iii) states that any provisions which differ from
                   this Agreement are offered by that Contributor
                   alone and not by any other party; and

                   iv) states that source code for the Program is
                   available from such Contributor, and informs
                   licensees how to obtain it in a reasonable manner
                   on or through a medium customarily used for
                   software exchange.

             When the Program is made available in source code form:
                   a) it must be made available under this Agreement;
                   and
                   b) a copy of this Agreement must be included with
                   each copy of the Program. 

             Contributors may not remove or alter any copyright notices
             contained within the Program.

             Each Contributor must identify itself as the originator of
             its Contribution, if any, in a manner that reasonably
             allows subsequent Recipients to identify the originator of
             the Contribution. 

             4. COMMERCIAL DISTRIBUTION

             Commercial distributors of software may accept certain
             responsibilities with respect to end users, business
             partners and the like. While this license is intended to
             facilitate the commercial use of the Program, the
             Contributor who includes the Program in a commercial
             product offering should do so in a manner which does not
             create potential liability for other Contributors.
             Therefore, if a Contributor includes the Program in a
             commercial product offering, such Contributor ("Commercial
             Contributor") hereby agrees to defend and indemnify every
             other Contributor ("Indemnified Contributor") against any
             losses, damages and costs (collectively "Losses") arising
             from claims, lawsuits and other legal actions brought by a
             third party against the Indemnified Contributor to the
             extent caused by the acts or omissions of such Commercial
             Contributor in connection with its distribution of the
             Program in a commercial product offering. The obligations
             in this section do not apply to any claims or Losses
             relating to any actual or alleged intellectual property
             infringement. In order to qualify, an Indemnified
             Contributor must: a) promptly notify the Commercial
             Contributor in writing of such claim, and b) allow the
             Commercial Contributor to control, and cooperate with the
             Commercial Contributor in, the defense and any related
             settlement negotiations. The Indemnified Contributor may
             participate in any such claim at its own expense.

             For example, a Contributor might include the Program in a
             commercial product offering, Product X. That Contributor
             is then a Commercial Contributor. If that Commercial
             Contributor then makes performance claims, or offers
             warranties related to Product X, those performance claims
             and warranties are such Commercial Contributor's
             responsibility alone. Under this section, the Commercial
             Contributor would have to defend claims against the other
             Contributors related to those performance claims and
             warranties, and if a court requires any other Contributor
             to pay any damages as a result, the Commercial Contributor
             must pay those damages.

             5. NO WARRANTY

             EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE
             PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
             WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
             IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
             CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
             FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
             responsible for determining the appropriateness of using
             and distributing the Program and assumes all risks
             associated with its exercise of rights under this
             Agreement, including but not limited to the risks and
             costs of program errors, compliance with applicable laws,
             damage to or loss of data, programs or equipment, and
             unavailability or interruption of operations. 

             6. DISCLAIMER OF LIABILITY
             EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER
             RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY
             FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
             OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
             LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
             LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
             (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
             OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE
             OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
             POSSIBILITY OF SUCH DAMAGES.

             7. GENERAL

             If any provision of this Agreement is invalid or
             unenforceable under applicable law, it shall not affect
             the validity or enforceability of the remainder of the
             terms of this Agreement, and without further action by the
             parties hereto, such provision shall be reformed to the
             minimum extent necessary to make such provision valid and
             enforceable.

             If Recipient institutes patent litigation against a
             Contributor with respect to a patent applicable to
             software (including a cross-claim or counterclaim in a
             lawsuit), then any patent licenses granted by that
             Contributor to such Recipient under this Agreement shall
             terminate as of the date such litigation is filed. In
             addition, If Recipient institutes patent litigation
             against any entity (including a cross-claim or
             counterclaim in a lawsuit) alleging that the Program
             itself (excluding combinations of the Program with other
             software or hardware) infringes such Recipient's
             patent(s), then such Recipient's rights granted under
             Section 2(b) shall terminate as of the date such
             litigation is filed.

             All Recipient's rights under this Agreement shall
             terminate if it fails to comply with any of the material
             terms or conditions of this Agreement and does not cure
             such failure in a reasonable period of time after becoming
             aware of such noncompliance. If all Recipient's rights
             under this Agreement terminate, Recipient agrees to cease
             use and distribution of the Program as soon as reasonably
             practicable. However, Recipient's obligations under this
             Agreement and any licenses granted by Recipient relating
             to the Program shall continue and survive. 

             Everyone is permitted to copy and distribute copies of
             this Agreement, but in order to avoid inconsistency the
             Agreement is copyrighted and may only be modified in the
             following manner. The Agreement Steward reserves the right
             to publish new versions (including revisions) of this
             Agreement from time to time. No one other than the
             Agreement Steward has the right to modify this Agreement.

             IBM is the initial Agreement Steward. IBM may assign the
             responsibility to serve as the Agreement Steward to a
             suitable separate entity. Each new version of the
             Agreement will be given a distinguishing version number.
             The Program (including Contributions) may always be
             distributed subject to the version of the Agreement under
             which it was received. In addition, after a new version of
             the Agreement is published, Contributor may elect to
             distribute the Program (including its Contributions) under
             the new version. Except as expressly stated in Sections
             2(a) and 2(b) above, Recipient receives no rights or
             licenses to the intellectual property of any Contributor
             under this Agreement, whether expressly, by implication,
             estoppel or otherwise. All rights in the Program not
             expressly granted under this Agreement are reserved.

             This Agreement is governed by the laws of the State of New
             York and the intellectual property laws of the United
             States of America. No party to this Agreement will bring a
             legal action under this Agreement more than one year after
             the cause of action arose. Each party waives its rights to
             a jury trial in any resulting litigation. 


*/

/* (C) COPYRIGHT International Business Machines Corp. 2001,2002          */

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <pwd.h>
#include <grp.h>

#include "pkcs11types.h"
#include "defs.h"
#include "host_defs.h"
#include "h_extern.h"
#include "tok_spec_struct.h"
#include "pkcs32.h"
#include "shared_memory.h"
#include "trace.h"

#include <sys/file.h>
#include <syslog.h>

// Function:  dlist_add_as_first()
//
// Adds the specified node to the start of the list
//
// Returns:  pointer to the start of the list
//
DL_NODE *dlist_add_as_first(DL_NODE * list, void *data)
{
	DL_NODE *node = NULL;

	if (!data)
		return list;

	node = (DL_NODE *) malloc(sizeof(DL_NODE));
	if (!node)
		return NULL;

	node->data = data;
	node->prev = NULL;
	node->next = list;
	if (list)
		list->prev = node;

	return node;
}

// Function:  dlist_add_as_last()
//
// Adds the specified node to the end of the list
//
// Returns:  pointer to the start of the list
//
DL_NODE *dlist_add_as_last(DL_NODE * list, void *data)
{
	DL_NODE *node = NULL;

	if (!data)
		return list;

	node = (DL_NODE *) malloc(sizeof(DL_NODE));
	if (!node)
		return NULL;

	node->data = data;
	node->next = NULL;

	if (!list) {
		node->prev = NULL;
		return node;
	} else {
		DL_NODE *temp = dlist_get_last(list);
		temp->next = node;
		node->prev = temp;

		return list;
	}
}

// Function:  dlist_find()
//
DL_NODE *dlist_find(DL_NODE * list, void *data)
{
	DL_NODE *node = list;

	while (node && node->data != data)
		node = node->next;

	return node;
}

// Function:  dlist_get_first()
//
// Returns the last node in the list or NULL if list is empty
//
DL_NODE *dlist_get_first(DL_NODE * list)
{
	DL_NODE *temp = list;

	if (!list)
		return NULL;

	while (temp->prev != NULL)
		temp = temp->prev;

	return temp;
}

// Function:  dlist_get_last()
//
// Returns the last node in the list or NULL if list is empty
//
DL_NODE *dlist_get_last(DL_NODE * list)
{
	DL_NODE *temp = list;

	if (!list)
		return NULL;

	while (temp->next != NULL)
		temp = temp->next;

	return temp;
}

//
//
CK_ULONG dlist_length(DL_NODE * list)
{
	DL_NODE *temp = list;
	CK_ULONG len = 0;

	while (temp) {
		len++;
		temp = temp->next;
	}

	return len;
}

//
//
DL_NODE *dlist_next(DL_NODE * node)
{
	if (!node)
		return NULL;

	return node->next;
}

//
//
DL_NODE *dlist_prev(DL_NODE * node)
{
	if (!node)
		return NULL;

	return node->prev;
}

//
//
void dlist_purge(DL_NODE * list)
{
	DL_NODE *node;

	if (!list)
		return;

	do {
		node = list->next;
		free(list);
		list = node;
	} while (list);
}

// Function:  dlist_remove_node()
//
// Attempts to remove the specified node from the list.  The caller is
// responsible for freeing the data associated with the node prior to
// calling this routine
//
DL_NODE *dlist_remove_node(DL_NODE * list, DL_NODE * node)
{
	DL_NODE *temp = list;

	if (!list || !node)
		return NULL;

	// special case:  removing head of the list
	//
	if (list == node) {
		temp = list->next;
		if (temp)
			temp->prev = NULL;

		free(list);
		return temp;
	}
	// we have no guarantee that the node is in the list
	// so search through the list to find it
	//
	while ((temp != NULL) && (temp->next != node))
		temp = temp->next;

	if (temp != NULL) {
		DL_NODE *next = node->next;

		temp->next = next;
		if (next)
			next->prev = temp;

		free(node);
	}

	return list;
}

// NOTE about Mutexes and cross process locking....
//
// The code uses 2 types of locks... internal locks to prevent threads within the same
// process space from stomping on each other  (pthread_mutex's suffice for 
// this).... and Cross Process Locks....
// On AIX we use it's variation of Posix semaphores for this.... Idealy on other
// platforms either POSIXSEMaphores or PTHREADXPL (pthreads xprocess lock) would
// be used.  On Linux unfortunatly  neither of these are available so we need to
// use the old standby of  SYSV semaphores (YECH.... GAG....)....  The only
// pieces which have been tested are the AIX and SYSV portions although 
// we expect that the others work correctly.
//
// we use alot more mutexes in the redesign than we did in the original
// design.  so instead of just the single global "pkcs_mutex" we have to
// deal with a number of mutexes.  so we'll make the mutex routines a
// bit more generic.
//

CK_RV _CreateMutex(MUTEX * mutex)
{
	// on AIX we make this a no-op since we assume that
	// the mutex was created in the initialization
	pthread_mutex_init(mutex, NULL);
	return CKR_OK;
}

CK_RV _DestroyMutex(MUTEX * mutex)
{
	// no-op in AIX
	pthread_mutex_destroy((pthread_mutex_t *) mutex);
	return CKR_OK;

}

CK_RV _LockMutex(MUTEX * mutex)
{
	pthread_mutex_lock(mutex);
	return CKR_OK;

}

CK_RV _UnlockMutex(MUTEX * mutex)
{
	pthread_mutex_unlock(mutex);
	return CKR_OK;

}

static int spinxplfd = -1;

CK_RV CreateXProcLock(void)
{
	CK_BYTE lockfile[PATH_MAX];
	struct group *grp;
	struct stat statbuf;
	mode_t mode = (S_IRUSR | S_IRGRP);

	if (spinxplfd == -1) {

		if (token_specific.t_creatlock != NULL) {
			spinxplfd = token_specific.t_creatlock();
			if (spinxplfd != -1)
				return CKR_OK;
			else
				return CKR_FUNCTION_FAILED;
		}

		/* create user lock file */
		sprintf(lockfile, "%s/%s/LCK..%s",
			LOCKDIR_PATH, SUB_DIR, SUB_DIR);

		if (stat(lockfile, &statbuf) == 0)
			spinxplfd = open(lockfile, O_RDONLY, mode);
		else {
			spinxplfd = open(lockfile, O_CREAT | O_RDONLY, mode);
			if (spinxplfd != -1) {
				/* umask may prevent correct mode,so set it. */
				if (fchmod(spinxplfd, mode) == -1) {
					OCK_SYSLOG(LOG_ERR, "fchmod(%s): %s\n",
						   lockfile, strerror(errno));
					goto err;
				}

				grp = getgrnam("pkcs11");
				if (grp != NULL) {
					if (fchown(spinxplfd, -1, grp->gr_gid)
					    == -1) {
						OCK_SYSLOG(LOG_ERR,
							   "fchown(%s): %s\n",
							   lockfile,
							   strerror(errno));
						goto err;
					}
				} else {
					OCK_SYSLOG(LOG_ERR, "getgrnam(): %s\n",
						   strerror(errno));
					goto err;
				}
			}
		}
		if (spinxplfd == -1) {
			OCK_SYSLOG(LOG_ERR, "open(%s): %s\n",
				   lockfile, strerror(errno));
			return CKR_FUNCTION_FAILED;
		}
	}

	return CKR_OK;

err:
	if (spinxplfd != -1)
		close(spinxplfd);
	return CKR_FUNCTION_FAILED;
}

void CloseXProcLock(void)
{
	if (spinxplfd != -1)
		close(spinxplfd);
}

CK_RV XProcLock(void)
{
	if (spinxplfd != -1)
		flock(spinxplfd, LOCK_EX);
	else
		TRACE_DEVEL("No file descriptor to lock with.\n");

	return CKR_OK;
}

CK_RV XProcUnLock(void)
{
	if (spinxplfd != -1)
		flock(spinxplfd, LOCK_UN);
	else
		TRACE_DEVEL("No file descriptor to unlock with.\n");

	return CKR_OK;
}

void XProcLock_Init(void)
{
	spinxplfd = -1;
}

//
//

extern CK_CHAR manuf[];
extern CK_CHAR model[];
extern CK_CHAR descr[];
extern CK_CHAR label[];

//
//
void init_slotInfo(void)
{
	memset(&slot_info.slotDescription, ' ',
	       sizeof(slot_info.slotDescription));
	memset(&slot_info.manufacturerID, ' ',
	       sizeof(slot_info.manufacturerID));

	memcpy(&slot_info.slotDescription, descr, strlen((char *)descr));
	memcpy(&slot_info.manufacturerID, manuf, strlen((char *)manuf));

	slot_info.hardwareVersion.major = 1;
	slot_info.hardwareVersion.minor = 0;
	slot_info.firmwareVersion.major = 1;
	slot_info.firmwareVersion.minor = 0;
	slot_info.flags = CKF_TOKEN_PRESENT | CKF_HW_SLOT;
}

//
//
void init_tokenInfo(void)
{
	CK_TOKEN_INFO_32 *token_info = NULL;

	token_info = &nv_token_data->token_info;

	memset(token_info->manufacturerID, ' ',
	       sizeof(token_info->manufacturerID));
	memset(token_info->model, ' ', sizeof(token_info->model));
	memset(token_info->serialNumber, ' ', sizeof(token_info->serialNumber));

	memcpy(token_info->label, nv_token_data->token_info.label, 32);

	memcpy(token_info->manufacturerID, manuf, strlen((char *)manuf));
	memcpy(token_info->model, model, strlen((char *)model));

	// use the 41-xxxxx serial number from the coprocessor
	//
	memcpy(token_info->serialNumber, "123", 3);

	// I don't see any API support for changing the clock so
	// we will use the system clock for the token's clock.
	//

	token_info->flags = CKF_RNG | CKF_LOGIN_REQUIRED | CKF_CLOCK_ON_TOKEN | CKF_SO_PIN_TO_BE_CHANGED;	// XXX New in v2.11 - KEY

	if (memcmp
	    (nv_token_data->user_pin_sha, "00000000000000000000",
	     SHA1_HASH_SIZE) != 0)
		token_info->flags |= CKF_USER_PIN_INITIALIZED;
	else
		token_info->flags |= CKF_USER_PIN_TO_BE_CHANGED;	// XXX New in v2.11 - KEY

	// For the release, we made these 
	// values as CK_UNAVAILABLE_INFORMATION
	//
	token_info->ulMaxSessionCount =
	    (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulSessionCount = (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulMaxRwSessionCount =
	    (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulRwSessionCount = (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulMaxPinLen = MAX_PIN_LEN;
	token_info->ulMinPinLen = MIN_PIN_LEN;
	token_info->ulTotalPublicMemory =
	    (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulFreePublicMemory =
	    (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulTotalPrivateMemory =
	    (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;
	token_info->ulFreePrivateMemory =
	    (CK_ULONG_32) CK_UNAVAILABLE_INFORMATION;

	token_info->hardwareVersion.major = 1;
	token_info->hardwareVersion.minor = 0;
	token_info->firmwareVersion.major = 1;
	token_info->firmwareVersion.minor = 0;

	memset(token_info->utcTime, ' ', sizeof(token_info->utcTime));
}

//
//
CK_RV init_token_data(CK_SLOT_ID slot_id)
{
	CK_RV rc;

	memset((char *)nv_token_data, 0, sizeof(nv_token_data));

	// the normal USER pin is not set when the token is initialized
	//
	memcpy(nv_token_data->user_pin_sha, "00000000000000000000",
	       SHA1_HASH_SIZE);
	memcpy(nv_token_data->so_pin_sha, default_so_pin_sha, SHA1_HASH_SIZE);

	memset(user_pin_md5, 0x0, MD5_HASH_SIZE);
	memcpy(so_pin_md5, default_so_pin_md5, MD5_HASH_SIZE);

	memcpy(nv_token_data->next_token_object_name, "00000000", 8);

	// generate the master key used for signing the Operation State information
	//                          `
	memset(nv_token_data->token_info.label, ' ',
	       sizeof(nv_token_data->token_info.label));
	memcpy(nv_token_data->token_info.label, label, strlen((char *)label));

	nv_token_data->tweak_vector.allow_weak_des = TRUE;
	nv_token_data->tweak_vector.check_des_parity = FALSE;
	nv_token_data->tweak_vector.allow_key_mods = TRUE;
	nv_token_data->tweak_vector.netscape_mods = TRUE;

	init_tokenInfo();

	if (token_specific.t_init_token_data) {
		rc = token_specific.t_init_token_data(slot_id);
		if (rc != CKR_OK)
			return rc;
	} else {
		//
		// FIXME: erase the token object index file (and all token objects)
		//
		rc = generate_master_key(master_key);
		if (rc != CKR_OK) {
			TRACE_DEVEL("generate_master_key failed.\n");
			return CKR_FUNCTION_FAILED;
		}

		rc = save_masterkey_so();
		if (rc != CKR_OK) {
			TRACE_DEVEL("save_masterkey_so failed.\n");
			return rc;
		}
	}

	rc = save_token_data(slot_id);

	return rc;
}

// Function:  compute_next_token_obj_name()
//
// Given a token object name (8 bytes in the range [0-9A-Z]) increment by one
// adjusting as necessary
//
// This gives us a namespace of 36^8 = 2,821,109,907,456 objects before wrapping around
//
CK_RV compute_next_token_obj_name(CK_BYTE * current, CK_BYTE * next)
{
	int val[8];
	int i;

	if (!current || !next) {
		TRACE_ERROR("Invalid function arguments.\n");
		return CKR_FUNCTION_FAILED;
	}
	// Convert to integral base 36
	//
	for (i = 0; i < 8; i++) {
		if (current[i] >= '0' && current[i] <= '9')
			val[i] = current[i] - '0';

		if (current[i] >= 'A' && current[i] <= 'Z')
			val[i] = current[i] - 'A' + 10;
	}

	val[0]++;

	i = 0;

	while (val[i] > 35) {
		val[i] = 0;

		if (i + 1 < 8) {
			val[i + 1]++;
			i++;
		} else {
			val[0]++;
			i = 0;	// start pass 2
		}
	}

	// now, convert back to [0-9A-Z]
	//
	for (i = 0; i < 8; i++) {
		if (val[i] < 10)
			next[i] = '0' + val[i];
		else
			next[i] = 'A' + val[i] - 10;
	}

	return CKR_OK;
}

//
//
CK_RV
build_attribute(CK_ATTRIBUTE_TYPE type,
		CK_BYTE * data, CK_ULONG data_len, CK_ATTRIBUTE ** attrib)
{
	CK_ATTRIBUTE *attr = NULL;

	attr = (CK_ATTRIBUTE *) malloc(sizeof(CK_ATTRIBUTE) + data_len);
	if (!attr) {
		TRACE_ERROR("%s\n", ock_err(ERR_HOST_MEMORY));
		return CKR_HOST_MEMORY;
	}
	attr->type = type;
	attr->ulValueLen = data_len;

	if (data_len > 0) {
		attr->pValue = (CK_BYTE *) attr + sizeof(CK_ATTRIBUTE);
		memcpy(attr->pValue, data, data_len);
	} else
		attr->pValue = NULL;

	*attrib = attr;

	return CKR_OK;
}

/*
 * Find an attribute in an attribute array.
 *
 * Returns CKR_FUNCTION_FAILED when attribute is not found,
 * CKR_ATTRIBUTE_TYPE_INVALID when length doesn't match the expected and
 * CKR_OK when values is returned in the `value` argument.
 */
CK_RV
find_bbool_attribute(CK_ATTRIBUTE *attrs, CK_ULONG attrs_len,
		     CK_ATTRIBUTE_TYPE type, CK_BBOOL *value)
{
	CK_ULONG i;

	for (i = 0; i < attrs_len; i++) {
		if (attrs[i].type == type) {
			/* Check size */
			if (attrs[i].ulValueLen != sizeof(*value))
				return CKR_ATTRIBUTE_TYPE_INVALID;

			/* Get value */
			*value = *((CK_BBOOL *) attrs[i].pValue);
		}
	}

	return CKR_FUNCTION_FAILED;
}

//
//
CK_RV
add_pkcs_padding(CK_BYTE * ptr,
		 CK_ULONG block_size, CK_ULONG data_len, CK_ULONG total_len)
{
	CK_ULONG i, pad_len;
	CK_BYTE pad_value;

	pad_len = block_size - (data_len % block_size);
	pad_value = (CK_BYTE) pad_len;

	if (data_len + pad_len > total_len) {
		TRACE_ERROR("The total length is too small to add padding.\n");
		return CKR_FUNCTION_FAILED;
	}
	for (i = 0; i < pad_len; i++)
		ptr[i] = pad_value;

	return CKR_OK;
}

//
//
CK_RV strip_pkcs_padding(CK_BYTE * ptr, CK_ULONG total_len, CK_ULONG * data_len)
{
	CK_BYTE pad_value;

	pad_value = ptr[total_len - 1];
	if (pad_value > total_len) {
		TRACE_ERROR("%s\n", ock_err(ERR_ENCRYPTED_DATA_INVALID));
		return CKR_ENCRYPTED_DATA_INVALID;
	}
	// thus, we have 'pad_value' bytes of 'pad_value' appended to the end
	//
	*data_len = total_len - pad_value;

	return CKR_OK;
}

//
//
CK_BYTE parity_adjust(CK_BYTE b)
{
	if (parity_is_odd(b) == FALSE)
		b = (b & 0xFE) | ((~b) & 0x1);

	return b;
}

//
//
CK_RV parity_is_odd(CK_BYTE b)
{
	b = ((b >> 4) ^ b) & 0x0f;
	b = ((b >> 2) ^ b) & 0x03;
	b = ((b >> 1) ^ b) & 0x01;

	if (b == 1)
		return TRUE;
	else
		return FALSE;
}

CK_RV attach_shm(CK_SLOT_ID slot_id, LW_SHM_TYPE **shm)
{
	CK_RV rc = CKR_OK;
	int ret;
	char buf[PATH_MAX];

	if (token_specific.t_attach_shm != NULL)
		return token_specific.t_attach_shm(slot_id, shm);

	XProcLock();

	/*
	 * Attach to an existing shared memory region or create it if it doesn't
	 * exists. When it's created (ret=0) the region is initialized with
	 * zeros.
	 */
	ret = sm_open(get_pk_dir(buf), 0666, (void**) shm, sizeof(**shm), 0);
	if (ret < 0) {
		TRACE_DEVEL("sm_open failed.\n");
		rc = CKR_FUNCTION_FAILED;
		goto done;
	}

done:
	XProcUnLock();
	return rc;
}

CK_RV detach_shm()
{
	CK_RV rc = CKR_OK;

	XProcLock();

	if (sm_close((void *)global_shm, 0)) {
		TRACE_DEVEL("sm_close failed.\n");
		rc = CKR_FUNCTION_FAILED;
	}

	XProcUnLock();

	return rc;
}

CK_RV get_sha_size(CK_ULONG mech, CK_ULONG *hsize)
{
	switch(mech) {
	case CKM_SHA_1:
		*hsize = SHA1_HASH_SIZE;
		break;
	case CKM_SHA256:
		*hsize = SHA2_HASH_SIZE;
		break;
	case CKM_SHA384:
		*hsize = SHA3_HASH_SIZE;
		break;
	case CKM_SHA512:
		*hsize = SHA5_HASH_SIZE;
		break;
	default:
		return CKR_MECHANISM_INVALID;
	}
	return CKR_OK;
}

/* Compute specified SHA using either software or token implementation */
CK_RV compute_sha(CK_BYTE * data, CK_ULONG len, CK_BYTE *hash, CK_ULONG mech)
{
	DIGEST_CONTEXT ctx;
	CK_ULONG hash_len;
	CK_RV rv;

	memset(&ctx, 0x0, sizeof(ctx));
	ctx.mech.mechanism = mech;
	
	rv = get_sha_size(mech, &hash_len);
	if (rv != CKR_OK)
		return rv;

	rv = sha_init(NULL, &ctx, &ctx.mech);
	if (rv != CKR_OK) {
		TRACE_DEBUG("failed to create digest.\n");
		return rv;
	}
	return sha_hash(NULL, FALSE, &ctx, data, len, hash, &hash_len);
}

/* Compute SHA1 using software implementation */
CK_RV compute_sha1(CK_BYTE * data, CK_ULONG len, CK_BYTE *hash)
{
	// XXX KEY
	DIGEST_CONTEXT ctx;
	CK_ULONG hash_len = SHA1_HASH_SIZE;

	memset(&ctx, 0x0, sizeof(ctx));

	sw_sha1_init(&ctx);
	if (ctx.context == NULL)
		return CKR_HOST_MEMORY;

	return sw_sha1_hash(&ctx, data, len, hash, &hash_len);
}

CK_RV compute_md5(CK_BYTE * data, CK_ULONG len, CK_BYTE * hash)
{
	MD5_CONTEXT ctx;

	memset(&ctx, 0x0, sizeof(ctx));

	ckm_md5_init(&ctx);
	ckm_md5_update(&ctx, data, len);
	ckm_md5_final(&ctx, hash, MD5_HASH_SIZE);

	return CKR_OK;
}

CK_RV get_keytype(CK_OBJECT_HANDLE hkey, CK_KEY_TYPE *keytype)
{
	CK_RV rc;
	OBJECT *key_obj = NULL;
	CK_ATTRIBUTE *attr = NULL;

	rc = object_mgr_find_in_map1(hkey, &key_obj);
	if (rc != CKR_OK) {
		TRACE_DEVEL("object_mgr_find_in_map1 failed.\n");
		return rc;
	}
	rc = template_attribute_find(key_obj->template, CKA_KEY_TYPE, &attr);
	if (rc == FALSE) {
		TRACE_ERROR("%s\n", ock_err(ERR_KEY_TYPE_INCONSISTENT));
		return CKR_KEY_TYPE_INCONSISTENT;
	} else {
		*keytype = *(CK_KEY_TYPE *)attr->pValue;
		return CKR_OK;
	}
}

CK_RV check_user_and_group()
{
	int i;
	uid_t uid, euid;
	struct passwd *pw, *epw;
	struct group *grp;

	/*
	 * Check for root user or Group PKCS#11 Membershp.
	 * Only these are allowed.
	 */
	uid = getuid();
	euid = geteuid();

	/* Root or effective Root is ok */
	if (uid == 0 && euid == 0)
		return CKR_OK;

	/*
	 * Check for member of group. SAB get login seems to not work
	 * with some instances of application invocations (particularly
	 * when forked). So we need to get the group information.
	 * Really need to take the uid and map it to a name.
	 */
	grp = getgrnam("pkcs11");
	if (grp == NULL) {
		OCK_SYSLOG(LOG_ERR, "getgrnam() failed: %s\n", strerror(errno));
		goto error;
	}

	if (getgid() == grp->gr_gid || getegid() == grp->gr_gid)
		return CKR_OK;
	/* Check if user or effective user is member of pkcs11 group */
	pw = getpwuid(uid);
	epw = getpwuid(euid);
	for (i = 0; grp->gr_mem[i]; i++) {
		if ((pw && (strncmp(pw->pw_name, grp->gr_mem[i],
		    strlen(pw->pw_name)) == 0)) ||
		    (epw && (strncmp(epw->pw_name, grp->gr_mem[i],
		    strlen(epw->pw_name)) == 0)))
			return CKR_OK;
	}

error:
	TRACE_ERROR("%s\n", ock_err(ERR_FUNCTION_FAILED));
	return CKR_FUNCTION_FAILED;
}

void copy_token_contents_sensibly(CK_TOKEN_INFO_PTR pInfo,
				  TOKEN_DATA *nv_token_data)
{
	memcpy(pInfo, &nv_token_data->token_info, sizeof(CK_TOKEN_INFO_32));
	pInfo->flags = nv_token_data->token_info.flags;
	pInfo->ulMaxPinLen = nv_token_data->token_info.ulMaxPinLen;
	pInfo->ulMinPinLen = nv_token_data->token_info.ulMinPinLen;

	if (nv_token_data->token_info.ulTotalPublicMemory ==
	    (CK_ULONG_32)CK_UNAVAILABLE_INFORMATION)
		pInfo->ulTotalPublicMemory = (CK_ULONG)CK_UNAVAILABLE_INFORMATION;
	else
		pInfo->ulTotalPublicMemory = nv_token_data->token_info.ulTotalPublicMemory;

	if (nv_token_data->token_info.ulFreePublicMemory ==
	    (CK_ULONG_32)CK_UNAVAILABLE_INFORMATION)
		pInfo->ulFreePublicMemory = (CK_ULONG)CK_UNAVAILABLE_INFORMATION;
	else
		pInfo->ulFreePublicMemory = nv_token_data->token_info.ulFreePublicMemory;

	if (nv_token_data->token_info.ulTotalPrivateMemory ==
	    (CK_ULONG_32)CK_UNAVAILABLE_INFORMATION)
		pInfo->ulTotalPrivateMemory = (CK_ULONG)CK_UNAVAILABLE_INFORMATION;
	else
		pInfo->ulTotalPrivateMemory = nv_token_data->token_info.ulTotalPrivateMemory;

	if (nv_token_data->token_info.ulFreePrivateMemory ==
	   (CK_ULONG_32)CK_UNAVAILABLE_INFORMATION)
		pInfo->ulFreePrivateMemory = (CK_ULONG)CK_UNAVAILABLE_INFORMATION;
	else
		pInfo->ulFreePrivateMemory = nv_token_data->token_info.ulFreePrivateMemory;

	pInfo->hardwareVersion = nv_token_data->token_info.hardwareVersion;
	pInfo->firmwareVersion = nv_token_data->token_info.firmwareVersion;
	pInfo->ulMaxSessionCount = ULONG_MAX - 1;
	/* pInfo->ulSessionCount is set at the API level */
	pInfo->ulMaxRwSessionCount = ULONG_MAX - 1;
	pInfo->ulRwSessionCount = CK_UNAVAILABLE_INFORMATION;
}
